DbContext Class

Definition

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.

public class DbContext : IDisposable, Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<IServiceProvider>
public class DbContext : IDisposable, Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<IServiceProvider>, Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies, Microsoft.EntityFrameworkCore.Internal.IDbContextPoolable, Microsoft.EntityFrameworkCore.Internal.IDbSetCache
public class DbContext : IDisposable, Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<IServiceProvider>, Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies, Microsoft.EntityFrameworkCore.Internal.IDbContextPoolable, Microsoft.EntityFrameworkCore.Internal.IDbQueryCache, Microsoft.EntityFrameworkCore.Internal.IDbSetCache
public class DbContext : IAsyncDisposable, IDisposable, Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<IServiceProvider>, Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies, Microsoft.EntityFrameworkCore.Internal.IDbContextPoolable, Microsoft.EntityFrameworkCore.Internal.IDbSetCache
Inheritance
DbContext
Implements
IInfrastructure<IServiceProvider> IDisposable Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies Microsoft.EntityFrameworkCore.Internal.IDbContextPoolable Microsoft.EntityFrameworkCore.Internal.IDbSetCache Microsoft.EntityFrameworkCore.Internal.IDbQueryCache IResettableService IAsyncDisposable

Remarks

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.

See DbContext lifetime, configuration, and initialization, Querying data with EF Core, Changing tracking, and Saving data with EF Core for more information and examples.

Constructors

DbContext()

Initializes a new instance of the DbContext class. The OnConfiguring(DbContextOptionsBuilder) method will be called to configure the database (and other options) to be used for this context.

DbContext(DbContextOptions)

Initializes a new instance of the DbContext class using the specified options. The OnConfiguring(DbContextOptionsBuilder) method will still be called to allow further configuration of the options.

Properties

ChangeTracker

Provides access to information and operations for entity instances this context is tracking.

ContextId

A unique identifier for the context instance and pool lease, if any.

Database

Provides access to database related information and operations for this context.

Model

The metadata about the shape of entities, the relationships between them, and how they map to the database. May not include all the information necessary to initialize the database.

Methods

Add(Object)

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

Add<TEntity>(TEntity)

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

AddAsync(Object, CancellationToken)

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

AddAsync<TEntity>(TEntity, CancellationToken)

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

AddRange(IEnumerable<Object>)

Begins tracking the given entities, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

AddRange(Object[])

Begins tracking the given entities, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

AddRangeAsync(IEnumerable<Object>, CancellationToken)

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

AddRangeAsync(Object[])

Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.

Attach(Object)

Begins tracking the given entity and entries reachable from the given entity using the Unchanged state by default, but see below for cases when a different state will be used.

Attach<TEntity>(TEntity)

Begins tracking the given entity and entries reachable from the given entity using the Unchanged state by default, but see below for cases when a different state will be used.

AttachRange(IEnumerable<Object>)

Begins tracking the given entities and entries reachable from the given entities using the Unchanged state by default, but see below for cases when a different state will be used.

AttachRange(Object[])

Begins tracking the given entities and entries reachable from the given entities using the Unchanged state by default, but see below for cases when a different state will be used.

ConfigureConventions(ModelConfigurationBuilder)

Override this method to set defaults and configure conventions before they run. This method is invoked before OnModelCreating(ModelBuilder).

Dispose()

Releases the allocated resources for this context.

DisposeAsync()

Releases the allocated resources for this context.

Entry(Object)

Gets an EntityEntry for the given entity. The entry provides access to change tracking information and operations for the entity.

Entry<TEntity>(TEntity)

Gets an EntityEntry<TEntity> for the given entity. The entry provides access to change tracking information and operations for the entity.

Find(Type, Object[])

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

Find<TEntity>(Object[])

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

FindAsync(Type, Object[], CancellationToken)

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

FindAsync(Type, Object[])

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

FindAsync<TEntity>(Object[], CancellationToken)

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

FindAsync<TEntity>(Object[])

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

FromExpression<TResult>(Expression<Func<IQueryable<TResult>>>)

Creates a queryable for given query expression.

OnConfiguring(DbContextOptionsBuilder)

Override this method to configure the database (and other options) to be used for this context. This method is called for each instance of the context that is created. The base implementation does nothing.

OnModelCreating(ModelBuilder)

Override this method to further configure the model that was discovered by convention from the entity types exposed in DbSet<TEntity> properties on your derived context. The resulting model may be cached and re-used for subsequent instances of your derived context.

Query<TQuery>()
Obsolete.

Creates a DbSet<TEntity> that can be used to query instances of TQuery.

Remove(Object)

Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called.

Remove<TEntity>(TEntity)

Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called.

RemoveRange(IEnumerable<Object>)

Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called.

RemoveRange(Object[])

Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called.

SaveChanges()

Saves all changes made in this context to the database.

SaveChanges(Boolean)

Saves all changes made in this context to the database.

SaveChangesAsync(Boolean, CancellationToken)

Saves all changes made in this context to the database.

SaveChangesAsync(CancellationToken)

Saves all changes made in this context to the database.

Set<TEntity>()

Creates a DbSet<TEntity> that can be used to query and save instances of TEntity.

Set<TEntity>(String)

Creates a DbSet<TEntity> for a shared-type entity type that can be used to query and save instances of TEntity.

Update(Object)

Begins tracking the given entity and entries reachable from the given entity using the Modified state by default, but see below for cases when a different state will be used.

Update<TEntity>(TEntity)

Begins tracking the given entity and entries reachable from the given entity using the Modified state by default, but see below for cases when a different state will be used.

UpdateRange(IEnumerable<Object>)

Begins tracking the given entities and entries reachable from the given entities using the Modified state by default, but see below for cases when a different state will be used.

UpdateRange(Object[])

Begins tracking the given entities and entries reachable from the given entities using the Modified state by default, but see below for cases when a different state will be used.

Events

SaveChangesFailed

An event fired if a call to SaveChanges or SaveChangesAsync fails with an exception.

SavedChanges

An event fired at the end of a call to SaveChanges or SaveChangesAsync

SavingChanges

An event fired at the beginning of a call to SaveChanges or SaveChangesAsync

Explicit Interface Implementations

IDbContextDependencies.ChangeDetector

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextDependencies.EntityFinderFactory

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextDependencies.EntityFinderSource

This API supports the Entity Framework Core infrastructure and is not intended to be used directly from your code. This API may change or be removed in future releases.

IDbContextDependencies.EntityGraphAttacher

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextDependencies.ExceptionDetector

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextDependencies.InfrastructureLogger

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextDependencies.QueryProvider

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextDependencies.QuerySource

This API supports the Entity Framework Core infrastructure and is not intended to be used directly from your code. This API may change or be removed in future releases.

IDbContextDependencies.SetSource

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextDependencies.StateManager

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextDependencies.UpdateLogger

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextPoolable.ClearLease()

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextPoolable.ResetState()
IDbContextPoolable.Resurrect(DbContextPoolConfigurationSnapshot)

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextPoolable.SetLease(DbContextLease)

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextPoolable.SetLeaseAsync(DbContextLease, CancellationToken)

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextPoolable.SetPool(IDbContextPool)

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbContextPoolable.SnapshotConfiguration()

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbQueryCache.GetOrAddQuery(IDbQuerySource, Type)

This API supports the Entity Framework Core infrastructure and is not intended to be used directly from your code. This API may change or be removed in future releases.

IDbSetCache.GetOrAddSet(IDbSetSource, String, Type)

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbSetCache.GetOrAddSet(IDbSetSource, Type)

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IDbSetCache.GetSets()

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IInfrastructure<IServiceProvider>.Instance

Gets the scoped IServiceProvider being used to resolve services.

This property is intended for use by extension methods that need to make use of services not directly exposed in the public API surface.

IResettableService.ResetState()

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

IResettableService.ResetStateAsync(CancellationToken)

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

Extension Methods

GetInfrastructure<T>(IInfrastructure<T>)

Gets the value from a property that is being hidden using IInfrastructure<T>.

This method is typically used by database providers (and other extensions). It is generally not used in application code.

CreateProxy(DbContext, Type, Object[])

Creates a proxy instance for an entity type if proxy creation has been turned on.

CreateProxy<TEntity>(DbContext, Action<TEntity>, Object[])

Creates a proxy instance for an entity type if proxy creation has been turned on.

CreateProxy<TEntity>(DbContext, Object[])

Creates a proxy instance for an entity type if proxy creation has been turned on.

Applies to