Understanding DbContext in Entity Framework Core

Entity Framework Core DbContext Class: Here will understand in detail about DbContext class. The Dbcontext class is very important in Entity Framework Core, which is used to communicate with the database. In short, we can say DbContext is the heart of Entity Framework Core.

In EF Core, the Dbcontext is used to manage the database connection. This means it is responsible to open and close the database connection while performing DB activity.

The Dbcontext also interacts with the database to perform crud operations. It is also responsible to map the result of SQL queries with our application Entity model class.

In DbContext the SaveChanges method is responsible for Transaction Management (will discuss this in detail further in this EF Core series).

How to Create DbContext in Asp.net Core application?

To use Dbcontext in the Asp.net Core application, first, we add a new class file to our .Net Core project and inherit the DbContext base class to it.

The ideal file name should be the project name with suffix as Context. Here will create a simple CMS-based project (blog). So we name our newly created class as BlogDbContext. 

pseudo-code of DbContext class looks like as shown below:

public class BlogDbContext : DbContext
{
        public BlogDbContext(DbContextOptions<BlogDbContext> options) : base(options)
        {

        }
		
}


PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee