Entity Framework Core DbContext

In simple terms, DbContext is a class in Entity Framework Core that you can inherit in your application and use to access the database and do all the operations there. DbContext can manage database connections, create tables/models and manage their relationships, perform CRUD (create read, update, and delete)operations, track changes, manage transactions, provide first-level caching of objects from the data source, etc. With EF Core, data access is done using a model. A model can be considered as a set of one or more entity classes and a context object that represents a session with the database. Let us see how we can add a DbContext and a model to our project.

First, we will create a model. Create a new folder named “Models” in the application, which we created in the previous tutorial installation of Entity Framework Core, and add a customer class.


Copy the following code to the Customer class.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace MyEFCoreApp.Model
{
    public class Customer
    {
        
       public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }
}

The next step is creating a DbContext. Add a new folder named Data and create a new class named AppDbContext and copy the following code. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MyEFCoreApp.Model;
namespace MyEFCoreApp.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {          
        }
        public DbSet<Customer> Customers { get; set; }       
    }
}


Our AppDbContext class is Inherited from DbContext class in Entity Framework Core. In the constructor of AppDbContext class, we need to pass DbContextOptions to the parent class. The DbContextOptions instance contains configuration information such as database providers to use, connection string, and any database-related configuration information.

To create a table in the database related to the Customer model, we added the following code.

      public DbSet<Customer> Customers { get; set; } 

Here, we defined a property of Type DbSet<TEntity>  that is mapped by default to the database table that takes the name of the DbSet<TEntity> property.

Next, we need to add a connection string in the appsettings.json file. Add the following string there.

"Connectionstrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=EFCoreApp;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

“(localdb)\mssqllocaldb” is the default local DB instance in SQL Server 2019, and the database name is EFCoreApp. We have also set Multiple Active Result Set (MARS) true. 

The next thing is registering the Application DB Context for dependency injection. This can be done in Startup.CS within ConfigureServices method as follows.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
        }

We are ready to do our first migration now. 

To create a table in the database for the Customer model we added, we need to use migration. Do the following steps for this.

  1. Go to Tools -> NuGet Package Manager -> Package Manager Console 
  2. In Package Manager Console, enter Add-Migration CreateCustomersTableAndDB and press enter key. You can see a folder named “Migrations” is created with the code to create the Customers table in the database.
  3. To create the database and the table in SQL Server, type update-database and press enter.

"CreateCustomersTableAndDB" is a name given to the migration. Any meaningful name can be given for the same. 


 

When update-database command is executed, the database will be created, and you can see it in Server Explorer in Visual studio.

 



In the next article, you can learn more about Entity Framework Core migrations.

 

 


Search