Adding DbContext to .NET Core Web API

What is DBContext?

DbContext or the Entity Framework Database Context file is the most important Entity Framework class because this class serves as the translator between the database tables and C# classes as we also know, C# Data Models. DBContext is able to understand both C# and SQL code, so it able to convert C# code into SQL understandable code and vice versa.

As the primary class responsible for interacting with the database, the DBContext includes, but is not limited to the following capabilities:
– Opens and manages connections to the database
Database operations such as adding, modifying, or deleting data from the database
Track changes – it keeps track of the changes that occurred on the entities after querying from the database
Caching – it provides first-level caching by default for objects that it is asked to retrieve from the data store
Data mapping – it includes a data mapper layer responsible for mapping the results of SQL queries to entity instances defined in your apps.


Adding your DbConext implementation

To use the DbContext in .NET Core Apps (Console, Web API, MVC) you need to first install the Entity Framework Core. To install Entity Framework Core in Visual Studio (I am using Visual Studio 2019) got to Package Manager Console. So, Tools > Nuget Package Manager > Package Manager Console

Then type: Install-Package Microsoft.EntityFrameworkCore

Entity Framework Core installation command

Now that you have installed the entity framework core package, you can start by creating your AppDbContext file. To create that file you need to:
1. Create a new C# class AppDbContext (Choose any name you want)
2. Inherit from the base class DbContext
3. Inject DbContextOptions<AppDbContext> into constructor and pass it to the base class
4. Define the DbSets of your Models. The name that you define for a DbSet in here will be used by the entity framework core to create your SQL tables.

I have a Student model in my solution, so this is how my AppDbContext looks like after I have followed the 4 steps above.

using EFCore.Data.Models;
using Microsoft.EntityFrameworkCore;

namespace EFCore.Data
{
    public class AppDbContext:DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }

        public DbSet<Student> Students { get; set; }
    }
}

So, this is all you need to do to set up your DbContext in Web API using Entity Framework Core.

You can also watch this clip for more details:

09. Adding Your Entity Framework Core DbContext File to Web API

Enjoyed this post? Subscribe to my YouTube channel for more great content. Your support is much appreciated. Thank you!


Check out my Udemy profile for more great content and exclusive learning resources! Thank you for your support.
Ervis Trupja - Udemy



Enjoyed this blog post? Share it with your friends and help spread the word! Don't keep all this knowledge to yourself.