Table of Contents

Class DbContext

Namespace
Microsoft.EntityFrameworkCore
Assembly
Microsoft.EntityFrameworkCore.dll

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 : IInfrastructure<IServiceProvider>, IDbContextDependencies, IDbSetCache, IDbContextPoolable, IResettableService, IDisposable, IAsyncDisposable
Inheritance
DbContext
Implements
Inherited Members
Extension Methods

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.

protected DbContext()

Remarks

See DbContext lifetime, configuration, and initialization for more information and examples.

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.

public DbContext(DbContextOptions options)

Parameters

options DbContextOptions

The options for this context.

Remarks

Properties

ChangeTracker

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

public virtual ChangeTracker ChangeTracker { get; }

Property Value

ChangeTracker

Remarks

See EF Core change tracking for more information and examples.

ContextId

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

public virtual DbContextId ContextId { get; }

Property Value

DbContextId

Remarks

This identifier is primarily intended as a correlation ID for logging and debugging such that it is easy to identify that multiple events are using the same or different context instances.

Database

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

public virtual DatabaseFacade Database { get; }

Property Value

DatabaseFacade

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.

public virtual IModel Model { get; }

Property Value

IModel

Remarks

See Modeling entity types and relationships for more information and examples.

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.

public virtual EntityEntry Add(object entity)

Parameters

entity object

The entity to add.

Returns

EntityEntry

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

Remarks

Use State to set the state of only a single entity.

See EF Core change tracking for more information and examples.

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.

public virtual ValueTask<EntityEntry> AddAsync(object entity, CancellationToken cancellationToken = default)

Parameters

entity object

The entity to add.

cancellationToken CancellationToken

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

Returns

ValueTask<EntityEntry>

A task that represents the asynchronous Add operation. The task result contains the EntityEntry for the entity. The entry provides access to change tracking information and operations for the entity.

Remarks

Use State to set the state of only a single entity.

This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used.

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.

See EF Core change tracking for more information and examples.

Exceptions

OperationCanceledException

If the CancellationToken is canceled.

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.

public virtual ValueTask<EntityEntry<TEntity>> AddAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = default) where TEntity : class

Parameters

entity TEntity

The entity to add.

cancellationToken CancellationToken

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

Returns

ValueTask<EntityEntry<TEntity>>

A task that represents the asynchronous Add operation. The task result contains the EntityEntry<TEntity> for the entity. The entry provides access to change tracking information and operations for the entity.

Type Parameters

TEntity

The type of the entity.

Remarks

This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used.

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.

See EF Core change tracking for more information and examples.

Exceptions

OperationCanceledException

If the CancellationToken is canceled.

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.

public virtual void AddRange(IEnumerable<object> entities)

Parameters

entities IEnumerable<object>

The entities to add.

Remarks

AddRange(params 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.

public virtual void AddRange(params object[] entities)

Parameters

entities object[]

The entities to add.

Remarks

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.

public virtual Task AddRangeAsync(IEnumerable<object> entities, CancellationToken cancellationToken = default)

Parameters

entities IEnumerable<object>

The entities to add.

cancellationToken CancellationToken

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

Returns

Task

A task that represents the asynchronous operation.

Remarks

This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used.

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.

See EF Core change tracking and Using AddRange, UpdateRange, AttachRange, and RemoveRange for more information and examples.

Exceptions

OperationCanceledException

If the CancellationToken is canceled.

AddRangeAsync(params 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.

public virtual Task AddRangeAsync(params object[] entities)

Parameters

entities object[]

The entities to add.

Returns

Task

A task that represents the asynchronous operation.

Remarks

This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used.

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.

See EF Core change tracking and Using AddRange, UpdateRange, AttachRange, and RemoveRange for more information and examples.

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.

public virtual EntityEntry<TEntity> Add<TEntity>(TEntity entity) where TEntity : class

Parameters

entity TEntity

The entity to add.

Returns

EntityEntry<TEntity>

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

Type Parameters

TEntity

The type of the entity.

Remarks

Use State to set the state of only a single entity.

See EF Core change tracking for more information and examples.

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.

public virtual EntityEntry Attach(object entity)

Parameters

entity object

The entity to attach.

Returns

EntityEntry

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

Remarks

Generally, no database interaction will be performed until SaveChanges() is called.

A recursive search of the navigation properties will be performed to find reachable entities that are not already being tracked by the context. All entities found will be tracked by the context.

For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Unchanged state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure only new entities will be inserted. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

For entity types without generated keys, the state set is always Unchanged.

Use State to set the state of only a single entity.

See EF Core change tracking for more information and examples.

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.

public virtual void AttachRange(IEnumerable<object> entities)

Parameters

entities IEnumerable<object>

The entities to attach.

Remarks

Generally, no database interaction will be performed until SaveChanges() is called.

A recursive search of the navigation properties will be performed to find reachable entities that are not already being tracked by the context. All entities found will be tracked by the context.

For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Unchanged state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure only new entities will be inserted. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

For entity types without generated keys, the state set is always Unchanged.

Use State to set the state of only a single entity.

See EF Core change tracking and Using AddRange, UpdateRange, AttachRange, and RemoveRange for more information and examples.

AttachRange(params 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.

public virtual void AttachRange(params object[] entities)

Parameters

entities object[]

The entities to attach.

Remarks

Generally, no database interaction will be performed until SaveChanges() is called.

A recursive search of the navigation properties will be performed to find reachable entities that are not already being tracked by the context. All entities found will be tracked by the context.

For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Unchanged state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure only new entities will be inserted. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

For entity types without generated keys, the state set is always Unchanged.

Use State to set the state of only a single entity.

See EF Core change tracking and Using AddRange, UpdateRange, AttachRange, and RemoveRange for more information and examples.

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.

public virtual EntityEntry<TEntity> Attach<TEntity>(TEntity entity) where TEntity : class

Parameters

entity TEntity

The entity to attach.

Returns

EntityEntry<TEntity>

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

Type Parameters

TEntity

The type of the entity.

Remarks

Generally, no database interaction will be performed until SaveChanges() is called.

A recursive search of the navigation properties will be performed to find reachable entities that are not already being tracked by the context. All entities found will be tracked by the context.

For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Unchanged state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure only new entities will be inserted. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

For entity types without generated keys, the state set is always Unchanged.

Use State to set the state of only a single entity.

See EF Core change tracking for more information and examples.

ConfigureConventions(ModelConfigurationBuilder)

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

protected virtual void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)

Parameters

configurationBuilder ModelConfigurationBuilder

The builder being used to set defaults and configure conventions that will be used to build the model for this context.

Remarks

If a model is explicitly set on the options for this context (via UseModel(IModel)) then this method will not be run. However, it will still run when creating a compiled model.

See Pre-convention model building in EF Core for more information and examples.

Dispose()

Releases the allocated resources for this context.

public virtual void Dispose()

Remarks

See DbContext lifetime, configuration, and initialization for more information and examples.

DisposeAsync()

Releases the allocated resources for this context.

public virtual ValueTask DisposeAsync()

Returns

ValueTask

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.

See DbContext lifetime, configuration, and initialization for more information and examples.

Entry(object)

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

public virtual EntityEntry Entry(object entity)

Parameters

entity object

The entity to get the entry for.

Returns

EntityEntry

The entry for the given entity.

Remarks

This method may be called on an entity that is not tracked. You can then set the State property on the returned entry to have the context begin tracking the entity in the specified state.

See Accessing tracked entities in EF Core for more information and examples.

Entry<TEntity>(TEntity)

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

public virtual EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class

Parameters

entity TEntity

The entity to get the entry for.

Returns

EntityEntry<TEntity>

The entry for the given entity.

Type Parameters

TEntity

The type of the entity.

Remarks

See Accessing tracked entities in EF Core for more information and examples.

Find(Type, params 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.

public virtual object? Find(Type entityType, params object?[]? keyValues)

Parameters

entityType Type

The type of entity to find.

keyValues object[]

The values of the primary key for the entity to be found.

Returns

object

The entity found, or null.

Remarks

See Using Find and FindAsync for more information and examples.

FindAsync(Type, params 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.

public virtual ValueTask<object?> FindAsync(Type entityType, params object?[]? keyValues)

Parameters

entityType Type

The type of entity to find.

keyValues object[]

The values of the primary key for the entity to be found.

Returns

ValueTask<object>

The entity found, or null.

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.

See Using Find and FindAsync for more information and examples.

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.

public virtual ValueTask<object?> FindAsync(Type entityType, object?[]? keyValues, CancellationToken cancellationToken)

Parameters

entityType Type

The type of entity to find.

keyValues object[]

The values of the primary key for the entity to be found.

cancellationToken CancellationToken

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

Returns

ValueTask<object>

The entity found, or null.

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.

See Using Find and FindAsync for more information and examples.

Exceptions

OperationCanceledException

If the CancellationToken is canceled.

FindAsync<TEntity>(params 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.

public virtual ValueTask<TEntity?> FindAsync<TEntity>(params object?[]? keyValues) where TEntity : class

Parameters

keyValues object[]

The values of the primary key for the entity to be found.

Returns

ValueTask<TEntity>

The entity found, or null.

Type Parameters

TEntity

The type of entity to find.

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.

See Using Find and FindAsync for more information and examples.

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.

public virtual ValueTask<TEntity?> FindAsync<TEntity>(object?[]? keyValues, CancellationToken cancellationToken) where TEntity : class

Parameters

keyValues object[]

The values of the primary key for the entity to be found.

cancellationToken CancellationToken

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

Returns

ValueTask<TEntity>

The entity found, or null.

Type Parameters

TEntity

The type of entity to find.

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.

See Using Find and FindAsync for more information and examples.

Exceptions

OperationCanceledException

If the CancellationToken is canceled.

Find<TEntity>(params 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.

public virtual TEntity? Find<TEntity>(params object?[]? keyValues) where TEntity : class

Parameters

keyValues object[]

The values of the primary key for the entity to be found.

Returns

TEntity

The entity found, or null.

Type Parameters

TEntity

The type of entity to find.

Remarks

See Using Find and FindAsync for more information and examples.

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

Creates a queryable for given query expression.

public virtual IQueryable<TResult> FromExpression<TResult>(Expression<Func<IQueryable<TResult>>> expression)

Parameters

expression Expression<Func<IQueryable<TResult>>>

The query expression to create.

Returns

IQueryable<TResult>

An IQueryable<T> representing the query.

Type Parameters

TResult

The result type of the query expression.

Remarks

See Querying data with EF Core for more information and examples.

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.

protected virtual void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

Parameters

optionsBuilder DbContextOptionsBuilder

A builder used to create or modify options for this context. Databases (and other extensions) typically define extension methods on this object that allow you to configure the context.

Remarks

In situations where an instance of DbContextOptions may or may not have been passed to the constructor, you can use IsConfigured to determine if the options have already been set, and skip some or all of the logic in OnConfiguring(DbContextOptionsBuilder).

See DbContext lifetime, configuration, and initialization for more information and examples.

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.

protected virtual void OnModelCreating(ModelBuilder modelBuilder)

Parameters

modelBuilder ModelBuilder

The builder being used to construct the model for this context. Databases (and other extensions) typically define extension methods on this object that allow you to configure aspects of the model that are specific to a given database.

Remarks

If a model is explicitly set on the options for this context (via UseModel(IModel)) then this method will not be run. However, it will still run when creating a compiled model.

See Modeling entity types and relationships for more information and examples.

Remove(object)

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

public virtual EntityEntry Remove(object entity)

Parameters

entity object

The entity to remove.

Returns

EntityEntry

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

Remarks

If the entity is already tracked in the Added state then the context will stop tracking the entity (rather than marking it as Deleted) since the entity was previously added to the context and does not exist in the database.

Any other reachable entities that are not already being tracked will be tracked in the same way that they would be if Attach(object) was called before calling this method. This allows any cascading actions to be applied when SaveChanges() is called.

Use State to set the state of only a single entity.

See EF Core change tracking for more information and examples.

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.

public virtual void RemoveRange(IEnumerable<object> entities)

Parameters

entities IEnumerable<object>

The entities to remove.

Remarks

If any of the entities are already tracked in the Added state then the context will stop tracking those entities (rather than marking them as Deleted) since those entities were previously added to the context and do not exist in the database.

Any other reachable entities that are not already being tracked will be tracked in the same way that they would be if AttachRange(IEnumerable<object>) was called before calling this method. This allows any cascading actions to be applied when SaveChanges() is called.

See EF Core change tracking and Using AddRange, UpdateRange, AttachRange, and RemoveRange for more information and examples.

RemoveRange(params object[])

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

public virtual void RemoveRange(params object[] entities)

Parameters

entities object[]

The entities to remove.

Remarks

If any of the entities are already tracked in the Added state then the context will stop tracking those entities (rather than marking them as Deleted) since those entities were previously added to the context and do not exist in the database.

Any other reachable entities that are not already being tracked will be tracked in the same way that they would be if AttachRange(params object[]) was called before calling this method. This allows any cascading actions to be applied when SaveChanges() is called.

See EF Core change tracking and Using AddRange, UpdateRange, AttachRange, and RemoveRange for more information and examples.

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.

public virtual EntityEntry<TEntity> Remove<TEntity>(TEntity entity) where TEntity : class

Parameters

entity TEntity

The entity to remove.

Returns

EntityEntry<TEntity>

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

Type Parameters

TEntity

The type of the entity.

Remarks

If the entity is already tracked in the Added state then the context will stop tracking the entity (rather than marking it as Deleted) since the entity was previously added to the context and does not exist in the database.

Any other reachable entities that are not already being tracked will be tracked in the same way that they would be if Attach<TEntity>(TEntity) was called before calling this method. This allows any cascading actions to be applied when SaveChanges() is called.

Use State to set the state of only a single entity.

See EF Core change tracking for more information and examples.

SaveChanges()

Saves all changes made in this context to the database.

public virtual int SaveChanges()

Returns

int

The number of state entries written to the database.

Remarks

This method will automatically call DetectChanges() to discover any changes to entity instances before saving to the underlying database. This can be disabled via AutoDetectChangesEnabled.

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.

See Saving data in EF Core for more information and examples.

Exceptions

DbUpdateException

An error is encountered while saving to the database.

DbUpdateConcurrencyException

A concurrency violation is encountered while saving to the database. A concurrency violation occurs when an unexpected number of rows are affected during save. This is usually because the data in the database has been modified since it was loaded into memory.

SaveChanges(bool)

Saves all changes made in this context to the database.

public virtual int SaveChanges(bool acceptAllChangesOnSuccess)

Parameters

acceptAllChangesOnSuccess bool

Indicates whether AcceptAllChanges() is called after the changes have been sent successfully to the database.

Returns

int

The number of state entries written to the database.

Remarks

This method will automatically call DetectChanges() to discover any changes to entity instances before saving to the underlying database. This can be disabled via AutoDetectChangesEnabled.

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.

See Saving data in EF Core for more information and examples.

Exceptions

DbUpdateException

An error is encountered while saving to the database.

DbUpdateConcurrencyException

A concurrency violation is encountered while saving to the database. A concurrency violation occurs when an unexpected number of rows are affected during save. This is usually because the data in the database has been modified since it was loaded into memory.

SaveChangesAsync(bool, CancellationToken)

Saves all changes made in this context to the database.

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

Parameters

acceptAllChangesOnSuccess bool

Indicates whether AcceptAllChanges() is called after the changes have been sent successfully to the database.

cancellationToken CancellationToken

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

Returns

Task<int>

A task that represents the asynchronous save operation. The task result contains the number of state entries written to the database.

Remarks

This method will automatically call DetectChanges() to discover any changes to entity instances before saving to the underlying database. This can be disabled via AutoDetectChangesEnabled.

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.

See Saving data in EF Core for more information and examples.

Exceptions

DbUpdateException

An error is encountered while saving to the database.

DbUpdateConcurrencyException

A concurrency violation is encountered while saving to the database. A concurrency violation occurs when an unexpected number of rows are affected during save. This is usually because the data in the database has been modified since it was loaded into memory.

OperationCanceledException

If the CancellationToken is canceled.

SaveChangesAsync(CancellationToken)

Saves all changes made in this context to the database.

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

Parameters

cancellationToken CancellationToken

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

Returns

Task<int>

A task that represents the asynchronous save operation. The task result contains the number of state entries written to the database.

Remarks

This method will automatically call DetectChanges() to discover any changes to entity instances before saving to the underlying database. This can be disabled via AutoDetectChangesEnabled.

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.

See Saving data in EF Core for more information and examples.

Exceptions

DbUpdateException

An error is encountered while saving to the database.

DbUpdateConcurrencyException

A concurrency violation is encountered while saving to the database. A concurrency violation occurs when an unexpected number of rows are affected during save. This is usually because the data in the database has been modified since it was loaded into memory.

OperationCanceledException

If the CancellationToken is canceled.

Set<TEntity>()

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

public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class

Returns

DbSet<TEntity>

A set for the given entity type.

Type Parameters

TEntity

The type of entity for which a set should be returned.

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.

See Querying data with EF Core and Changing tracking for more information and examples.

Set<TEntity>(string)

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

public virtual DbSet<TEntity> Set<TEntity>(string name) where TEntity : class

Parameters

name string

The name for the shared-type entity type to use.

Returns

DbSet<TEntity>

A set for the given entity type.

Type Parameters

TEntity

The type of entity for which a set should be returned.

Remarks

Shared-type entity types are typically used for the join entity in many-to-many relationships.

See Querying data with EF Core, Changing tracking, and Shared entity types for more information and examples.

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.

public virtual EntityEntry Update(object entity)

Parameters

entity object

The entity to update.

Returns

EntityEntry

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

Remarks

Generally, no database interaction will be performed until SaveChanges() is called.

A recursive search of the navigation properties will be performed to find reachable entities that are not already being tracked by the context. All entities found will be tracked by the context.

For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Modified state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure new entities will be inserted, while existing entities will be updated. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

For entity types without generated keys, the state set is always Modified.

Use State to set the state of only a single entity.

See EF Core change tracking for more information and examples.

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.

public virtual void UpdateRange(IEnumerable<object> entities)

Parameters

entities IEnumerable<object>

The entities to update.

Remarks

Generally, no database interaction will be performed until SaveChanges() is called.

A recursive search of the navigation properties will be performed to find reachable entities that are not already being tracked by the context. All entities found will be tracked by the context.

For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Modified state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure new entities will be inserted, while existing entities will be updated. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

For entity types without generated keys, the state set is always Modified.

Use State to set the state of only a single entity.

See EF Core change tracking and Using AddRange, UpdateRange, AttachRange, and RemoveRange for more information and examples.

UpdateRange(params 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.

public virtual void UpdateRange(params object[] entities)

Parameters

entities object[]

The entities to update.

Remarks

Generally, no database interaction will be performed until SaveChanges() is called.

A recursive search of the navigation properties will be performed to find reachable entities that are not already being tracked by the context. All entities found will be tracked by the context.

For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Modified state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure new entities will be inserted, while existing entities will be updated. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

For entity types without generated keys, the state set is always Modified.

Use State to set the state of only a single entity.

See EF Core change tracking and Using AddRange, UpdateRange, AttachRange, and RemoveRange for more information and examples.

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.

public virtual EntityEntry<TEntity> Update<TEntity>(TEntity entity) where TEntity : class

Parameters

entity TEntity

The entity to update.

Returns

EntityEntry<TEntity>

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

Type Parameters

TEntity

The type of the entity.

Remarks

Generally, no database interaction will be performed until SaveChanges() is called.

A recursive search of the navigation properties will be performed to find reachable entities that are not already being tracked by the context. All entities found will be tracked by the context.

For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Modified state. If the primary key value is not set then it will be tracked in the Added state. This helps ensure new entities will be inserted, while existing entities will be updated. An entity is considered to have its primary key value set if the primary key property is set to anything other than the CLR default for the property type.

For entity types without generated keys, the state set is always Modified.

Use State to set the state of only a single entity.

See EF Core change tracking for more information and examples.

Events

SaveChangesFailed

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

public event EventHandler<SaveChangesFailedEventArgs>? SaveChangesFailed

Event Type

EventHandler<SaveChangesFailedEventArgs>

Remarks

See Saving data in EF Core and EF Core events for more information and examples.

SavedChanges

An event fired at the end of a call to or

public event EventHandler<SavedChangesEventArgs>? SavedChanges

Event Type

EventHandler<SavedChangesEventArgs>

Remarks

See Saving data in EF Core and EF Core events for more information and examples.

SavingChanges

An event fired at the beginning of a call to or

public event EventHandler<SavingChangesEventArgs>? SavingChanges

Event Type

EventHandler<SavingChangesEventArgs>

Remarks

See Saving data in EF Core and EF Core events for more information and examples.