Table of Contents

Class DbSet<TEntity>

Namespace
Microsoft.EntityFrameworkCore
Assembly
Microsoft.EntityFrameworkCore.dll

A DbSet<TEntity> can be used to query and save instances of TEntity. LINQ queries against a DbSet<TEntity> will be translated into queries against the database.

public abstract class DbSet<TEntity> : IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable, IInfrastructure<IServiceProvider>, IListSource where TEntity : class

Type Parameters

TEntity

The type of entity being operated on by this set.

Inheritance
DbSet<TEntity>
Implements
IQueryable<TEntity>
IEnumerable<TEntity>
Derived
Inherited Members
Extension Methods

Remarks

The results of a LINQ query against a DbSet<TEntity> will contain the results returned from the database and may not reflect changes made in the context that have not been persisted to the database. For example, the results will not contain newly added entities and may still contain entities that are marked for deletion.

Depending on the database being used, some parts of a LINQ query against a DbSet<TEntity> may be evaluated in memory rather than being translated into a database query.

DbSet<TEntity> objects are usually obtained from a DbSet<TEntity> property on a derived DbContext or from the Set<TEntity>() method.

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, Querying data with EF Core, and Changing tracking for more information and examples.

Constructors

DbSet()

protected DbSet()

Properties

EntityType

The IEntityType metadata associated with this set.

public abstract IEntityType EntityType { get; }

Property Value

IEntityType

Local

Gets a LocalView<TEntity> that represents a local view of all Added, Unchanged, and Modified entities in this set.

public virtual LocalView<TEntity> Local { get; }

Property Value

LocalView<TEntity>

Remarks

This local view will stay in sync as entities are added or removed from the context. Likewise, entities added to or removed from the local view will automatically be added to or removed from the context.

This property can be used for data binding by populating the set with data, for example by using the Load<TSource>(IQueryable<TSource>) extension method, and then binding to the local data through this property by calling ToObservableCollection() for WPF binding, or ToBindingList() for WinForms.

Note that this method calls DetectChanges() unless AutoDetectChangesEnabled has been set to false.

See Local views of tracked entities in EF Core for more information and examples.

Methods

Add(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 entity)

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.

Remarks

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

See EF Core change tracking for more information and examples.

AddAsync(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 entity, CancellationToken cancellationToken = default)

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.

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.

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

See EF Core change tracking for more information and examples.

Exceptions

OperationCanceledException

If the CancellationToken is canceled.

AddRange(IEnumerable<TEntity>)

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<TEntity> entities)

Parameters

entities IEnumerable<TEntity>

The entities to add.

Remarks

AddRange(params TEntity[])

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 TEntity[] entities)

Parameters

entities TEntity[]

The entities to add.

Remarks

AddRangeAsync(IEnumerable<TEntity>, CancellationToken)

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 Task AddRangeAsync(IEnumerable<TEntity> entities, CancellationToken cancellationToken = default)

Parameters

entities IEnumerable<TEntity>

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.

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 TEntity[])

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 Task AddRangeAsync(params TEntity[] entities)

Parameters

entities TEntity[]

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.

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

AsAsyncEnumerable()

Returns this object typed as IAsyncEnumerable<T>.

public virtual IAsyncEnumerable<TEntity> AsAsyncEnumerable()

Returns

IAsyncEnumerable<TEntity>

This object.

Remarks

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

AsQueryable()

Returns this object typed as IQueryable<T>.

public virtual IQueryable<TEntity> AsQueryable()

Returns

IQueryable<TEntity>

This object.

Remarks

This is a convenience method to help with disambiguation of extension methods in the same namespace that extend both interfaces.

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

Attach(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 entity)

Parameters

entity TEntity

The entity to attach.

Returns

EntityEntry<TEntity>

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<TEntity>)

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<TEntity> entities)

Parameters

entities IEnumerable<TEntity>

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 TEntity[])

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 TEntity[] entities)

Parameters

entities TEntity[]

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.

Entry(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 entity)

Parameters

entity TEntity

The entity to get the entry for.

Returns

EntityEntry<TEntity>

The entry for the given entity.

Remarks

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

Find(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(params object?[]? keyValues)

Parameters

keyValues object[]

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

Returns

TEntity

The entity found, or null.

Remarks

See Using Find and FindAsync for more information and examples.

FindAsync(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(params object?[]? keyValues)

Parameters

keyValues object[]

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

Returns

ValueTask<TEntity>

The entity found, or null.

Remarks

See Using Find and FindAsync for more information and examples.

FindAsync(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(object?[]? keyValues, CancellationToken cancellationToken)

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.

Remarks

See Using Find and FindAsync for more information and examples.

Exceptions

OperationCanceledException

If the CancellationToken is canceled.

GetAsyncEnumerator(CancellationToken)

Returns an IAsyncEnumerator<T> which when enumerated will asynchronously execute a query against the database.

public virtual IAsyncEnumerator<TEntity> GetAsyncEnumerator(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

A CancellationToken that may be used to cancel the asynchronous iteration.

Returns

IAsyncEnumerator<TEntity>

The query results.

Remarks

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

Remove(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 entity)

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.

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) 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<TEntity>)

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

public virtual void RemoveRange(IEnumerable<TEntity> entities)

Parameters

entities IEnumerable<TEntity>

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<TEntity>) 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 TEntity[])

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

public virtual void RemoveRange(params TEntity[] entities)

Parameters

entities TEntity[]

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 TEntity[]) 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.

Update(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 entity)

Parameters

entity TEntity

The entity to update.

Returns

EntityEntry<TEntity>

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<TEntity>)

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<TEntity> entities)

Parameters

entities IEnumerable<TEntity>

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 TEntity[])

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 TEntity[] entities)

Parameters

entities TEntity[]

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.