DbContext

A session with the database that can be used to query and save instances of your entities

Overview1

A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns. Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This includes both parallel execution of async queries and any explicit concurrent use from multiple threads. Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute in parallel. See Avoiding DbContext threading issues for more information and examples.

Typically you create a class that derives from DbContext and contains DbSet<TEntity> properties for each entity in the model. If the DbSet<TEntity> properties have a public setter, they are automatically initialized when the instance of the derived context is created.

Override the OnConfiguring(DbContextOptionsBuilder) method to configure the database (and other options) to be used for the context. Alternatively, if you would rather perform configuration externally instead of inline in your context, you can use DbContextOptionsBuilder<TContext> (or DbContextOptionsBuilder) to externally create an instance of DbContextOptions<TContext> (or DbContextOptions) and pass it to a base constructor of DbContext.

The model is discovered by running a set of conventions over the entity classes found in the DbSet<TEntity> properties on the derived context. To further configure the model that is discovered by convention, you can override the OnModelCreating(ModelBuilder) method.

DbContext Lifetime, Configuration, and Initialization

The lifetime of a DbContext begins when the instance is created and ends when the instance is disposed. A DbContext instance is designed to be used for a single unit-of-work. This means that the lifetime of a DbContext instance is usually very short.
A typical unit-of-work when using Entity Framework Core (EF Core) involves:

  • Creation of a DbContext instance
  • Tracking of entity instances by the context. Entities become tracked by
    • Being returned from a query
    • Being added or attached to the context
  • Changes are made to the tracked entities as needed to implement the business rule
  • SaveChanges or SaveChangesAsync is called. EF Core detects the changes made and writes them to the database.
  • The DbContext instance is disposed

It is very important to dispose the DbContext after use. This ensures both that any unmanaged resources are freed, and that any events or other hooks are unregistered so as to prevent memory leaks in case the instance remains referenced.

  • DbContext is not thread-safe. Do not share contexts between threads. Make sure to await all async calls before continuing to use the context instance.
  • An InvalidOperationException thrown by EF Core code can put the context into an unrecoverable state. Such exceptions indicate a program error and are not designed to be recovered from.