DbContext Class

Namespace: Microsoft.EntityFrameworkCore

Overview

Represents a session around a database. This is the main class used when interacting with Entity Framework Core. It is the entry point for querying and saving data.

The DbContext class is the core of Entity Framework Core. It represents a session with the database and is the bridge between your application code and the database. You typically create a class that inherits from DbContext and define DbSet<TEntity> properties for each entity in your domain model that you want to query and save.

Constructors

public DbContext()

Initializes a new instance of the DbContext class.

public DbContext(DbContextOptions options)

Initializes a new instance of the DbContext class with the given options.

Parameters

options

The options for configuring the context. This value is typically retrieved from a derived context.

Properties

public DbContextId ContextId { get; }

Gets a unique identifier for this instance of the context.

public ChangeTracker ChangeTracker { get; }

Gets an object that represents the change tracker for this context instance.

public ModelConfigurationBuilder ModelConfigurationBuilder { get; }

Gets a model configuration builder that can be used to configure the model.

Methods

public virtual int SaveChanges()

Saves all changes made in this context to the underlying database.

Returns

The number of state entries written to the underlying database.

public virtual Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)

Saves all changes made in this context to the underlying database.

Parameters

cancellationToken

A CancellationToken to observe while waiting for the task to complete.

Returns

A task that represents the asynchronous save operation. The value of the TResult parameter contains the number of state entries written to the underlying database.

public virtual void Dispose()

Disposes the context instance.

protected virtual void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

Configures the context to be used with a specific database provider and other options.

Parameters

optionsBuilder

The options builder to use when configuring the context.

protected virtual void OnModelCreating(ModelBuilder modelBuilder)

Configures the model for this context.

Parameters

modelBuilder

The builder being used to construct the model for this context.

Remarks

When you create a class that inherits from DbContext, you typically add DbSet<TEntity> properties to represent the collections of entities in your domain model. Entity Framework Core will automatically create tables in the database for these entities based on their properties and relationships.

The DbContext manages the state of your entities, including tracking changes, concurrency, and relationships. When you call SaveChanges() or SaveChangesAsync(), the context determines which entities have been added, modified, or deleted and generates the appropriate SQL commands to synchronize the database with your in-memory model.

It's important to dispose of your DbContext instances when you are finished with them to release any database connections and other resources. This is commonly done using a using statement in C#.

Examples

Basic Usage


using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }
}

// --- In your application code ---
using (var context = new BloggingContext())
{
    var blog = new Blog { Url = "http://example.com" };
    context.Blogs.Add(blog);
    context.SaveChanges();
}
            

Configuring with Dependency Injection


// --- In Startup.cs (or equivalent) ---
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

// --- In a controller or service ---
public class BlogsController : Controller
{
    private readonly BloggingContext _context;

    public BlogsController(BloggingContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        return View(_context.Blogs.ToList());
    }
}