How to use the DbContext in Entity Framework Core

Take advantage of the DbContext in Entity Framework Core to connect to a database and perform CRUD operations using CLR objects

Microsoft’s Entity Framework is an open-source object-relational mapper, or ORM, for ADO.Net that helps you isolate the object model of your application from the data model. Entity Framework simplifies data access in your application by allowing you to write code to perform CRUD (Create, Read, Update, and Delete) operations without having to know how the data is persisted in the underlying database.

The DbContext acts as a bridge between the domain classes and the database. In this article we will examine how we can configure the DbContext using an instance of DbContextOptions to connect to a database and perform CRUD operations using the Entity Framework Core provider.

DbContext explained

The DbContext is an integral component of the Entity Framework that represents a connection session with the database. You can take advantage of the DbContext to query data into your entities or save your entities to the underlying database. The DbContext in Entity Framework Core has a number of responsibilities:

  • Managing connections
  • Querying data from the database
  • Saving data to the database
  • Change tracking
  • Caching
  • Transaction management

In the sections that follow, we will explore how we can work with the DbContext in ASP.Net Core.

Create an ASP.Net Core application in Visual Studio

We’ll start by creating an ASP.Net Core application. Note that this post assumes that Visual Studio 2017 is already installed in your system. If you don’t have Visual Studio 2017 installed, you can download a copy here. Then follow these steps to create a new ASP.Net Core project.

  1. Launch the Visual Studio 2017 IDE.
  2. Click File -> New -> Project.
  3. Select the “ASP.Net Core Web Application” project template.
  4. Specify the name and location for your project.
  5. Click OK.
  6. In the “New ASP.Net Core Web Application” dialog window, select .Net Core.
  7. Select ASP.Net Core 2.1 from the drop-down list. 
  8. Select “Web API” as the project template. 
  9. Ignore the “Enable Docker support” checkbox; we won’t be using Docker here.
  10. Ensure that the message “No Authentication” is displayed; we won’t be needing this either. 
  11. Click OK

And that’s it! We will use this application to explore Entity Framework Core in the sections that follow.

Create a new DbContext in Entity Framework Core

To create a custom Context class, you should extend the DbContext base class in Entity Framework Core as shown below.

public class CustomContext : DbContext
    {
        public CustomContext(DbContextOptions options) : base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
           //Write your code here to configure the context
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //Write your code here to configure the model
        }
    }

Refer to the CustomContext class above. Note that it accepts a reference to an instance of the DbContextOptions class. This instance contains the configuration information needed by the DbContext. You can also configure the DbContext using the OnConfiguring method. The OnModelCreating method, which accepts a reference to an instance of the ModelBuilder class as an argument, is used to configure the model.

In the DbContext class, you typically have the DbSet<TEntity> properties of entities as shown in the code snippet below.

public class CustomContext : DbContext
    {
        public CustomContext(DbContextOptions options) : base(options)
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }
        public DbSet<Author> Authors { get; set; }
        public DbSet<Blog> Blogs { get; set; }
    }

Register the DbContext with the Entity Framework Core runtime

Next, you should register your custom DbContext class as a service in the IServiceCollection via the ConfigureServices method of the Startup class.

     public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion
            (CompatibilityVersion.Version_2_1);
            services.AddDbContext<CustomContext>(options =>
             options.UseSqlServer
             (Configuration.GetConnectionString(“TestConnection”)));
        }

The connection string is obtained using the IConfiguration instance. The AddDbContext extension method is used to register the DbContext as a service. Note how a reference to DbContextOptionsBuilder is used to configure the DbContextOptions. The UseSqlServer extension method is used to register the SQL Server database provider with the Entity Framework Core runtime.

Alternatively, you can override the OnConfigure method to register the SQL Server database provider as shown in the code snippet below.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("TestConnection");
        }
    }

Use the DbContext with dependency injection

To use the custom DbContext we implemented in the controller methods, you should take advantage of dependency injection. The following code snippet illustrates how this can be achieved.

public class ValuesController : ControllerBase
    {
        private CustomContext dbContext;
        public ValuesController(CustomContext customContext)
        {
            dbContext = customContext;
        }
       //Other methods
    }

And that’s all you need to do. You can now leverage the instance of the CustomContext class in your controller methods to perform CRUD operations.

The DbContext is conceptually like the ObjectContext. Representing a combination of the unit of work and repository design patterns, the DbContext is responsible for any interaction between the application and the database in use. I’ll discuss additional aspects of Entity Framework Core in future posts here.

Copyright © 2018 IDG Communications, Inc.