Share via


DbSet<TEntity>.Attach(TEntity) Method

Definition

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 Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<TEntity> Attach (TEntity entity);
abstract member Attach : 'Entity -> Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<'Entity (requires 'Entity : null)>
override this.Attach : 'Entity -> Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<'Entity (requires 'Entity : null)>
Public Overridable Function Attach (entity As TEntity) As EntityEntry(Of TEntity)

Parameters

entity
TEntity

The entity to attach.

Returns

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.

Applies to