Class ChangeTracker
- Namespace
- Microsoft.EntityFrameworkCore.ChangeTracking
- Assembly
- Microsoft.EntityFrameworkCore.dll
Provides access to change tracking information and operations for entity instances the context is tracking. Instances of this class are typically obtained from ChangeTracker and it is not designed to be directly constructed in your application code.
public class ChangeTracker : IResettableService
- Inheritance
-
ChangeTracker
- Implements
- Inherited Members
- Extension Methods
Remarks
See EF Core change tracking for more information and examples.
Constructors
ChangeTracker(DbContext, IStateManager, IChangeDetector, IModel, IEntityEntryGraphIterator)
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.
[EntityFrameworkInternal]
public ChangeTracker(DbContext context, IStateManager stateManager, IChangeDetector changeDetector, IModel model, IEntityEntryGraphIterator graphIterator)
Parameters
context
DbContextstateManager
IStateManagerchangeDetector
IChangeDetectormodel
IModelgraphIterator
IEntityEntryGraphIterator
Properties
AutoDetectChangesEnabled
Gets or sets a value indicating whether the DetectChanges() method is called automatically by methods of DbContext and related classes.
public virtual bool AutoDetectChangesEnabled { get; set; }
Property Value
Remarks
The default value is true. This ensures the context is aware of any changes to tracked entity instances before performing operations such as SaveChanges() or returning change tracking information. If you disable automatic detect changes then you must ensure that DetectChanges() is called when entity instances have been modified. Failure to do so may result in some changes not being persisted during SaveChanges() or out-of-date change tracking information being returned.
See EF Core change tracking for more information and examples.
CascadeDeleteTiming
Gets or sets a value indicating when a dependent/child entity will have its state set to Deleted once its parent/principal entity has been marked as Deleted. The default value isImmediate.
public virtual CascadeTiming CascadeDeleteTiming { get; set; }
Property Value
Remarks
Dependent/child entities are only deleted automatically when the relationship is configured with Microsoft.EntityFrameworkCore.DeleteBehavior.Cascade. This is set by default for required relationships.
See EF Core change tracking for more information and examples.
Context
Gets the context this change tracker belongs to.
public virtual DbContext Context { get; }
Property Value
DebugView
Expand this property in the debugger for a human-readable view of the entities being tracked.
Warning: Do not rely on the format of the debug strings. They are designed for debugging only and may change arbitrarily between releases.
See EF Core change tracking for more information and examples.
public virtual DebugView DebugView { get; }
Property Value
DeleteOrphansTiming
Gets or sets a value indicating when a dependent/child entity will have its state set to Deleted once severed from a parent/principal entity through either a navigation or foreign key property being set to null. The default value is Immediate.
public virtual CascadeTiming DeleteOrphansTiming { get; set; }
Property Value
Remarks
Dependent/child entities are only deleted automatically when the relationship is configured with Microsoft.EntityFrameworkCore.DeleteBehavior.Cascade. This is set by default for required relationships.
See EF Core change tracking for more information and examples.
LazyLoadingEnabled
Gets or sets a value indicating whether navigation properties for tracked entities will be loaded on first access.
public virtual bool LazyLoadingEnabled { get; set; }
Property Value
Remarks
The default value is true. However, lazy loading will only occur for navigation properties of entities that have also been configured in the model for lazy loading.
QueryTrackingBehavior
Gets or sets the tracking behavior for LINQ queries run against the context. Disabling change tracking is useful for read-only scenarios because it avoids the overhead of setting up change tracking for each entity instance. You should not disable change tracking if you want to manipulate entity instances and persist those changes to the database using SaveChanges().
public virtual QueryTrackingBehavior QueryTrackingBehavior { get; set; }
Property Value
Remarks
This method sets the default behavior for the context, but you can override this behavior for individual queries using the AsNoTracking<TEntity>(IQueryable<TEntity>) and AsTracking<TEntity>(IQueryable<TEntity>) methods.
The default value is TrackAll. This means the change tracker will keep track of changes for all entities that are returned from a LINQ query.
Methods
AcceptAllChanges()
Accepts all changes made to entities in the context. It will be assumed that the tracked entities represent the current state of the database. This method is typically called by SaveChanges() after changes have been successfully saved to the database.
public virtual void AcceptAllChanges()
CascadeChanges()
Forces immediate cascading deletion of child/dependent entities when they are either severed from a required parent/principal entity, or the required parent/principal entity is itself deleted. See Microsoft.EntityFrameworkCore.DeleteBehavior.
public virtual void CascadeChanges()
Remarks
This method is usually used when CascadeDeleteTiming and/or DeleteOrphansTiming have been set to Never to manually force the deletes to have at a time controlled by the application.
This method calls DetectChanges() to ensure the returned value is accurate. Since detecting changes can be slow, consider temporarily setting AutoDetectChangesEnabled to prevent detecting changes in situations where the state is known to be up-to-date.
See EF Core change tracking for more information and examples.
Clear()
Stops tracking all currently tracked entities.
public virtual void Clear()
Remarks
DbContext is designed to have a short lifetime where a new instance is created for each unit-of-work. This manner means all tracked entities are discarded when the context is disposed at the end of each unit-of-work. However, clearing all tracked entities using this method may be useful in situations where creating a new context instance is not practical.
This method should always be preferred over detaching every tracked entity. Detaching entities is a slow process that may have side effects. This method is much more efficient at clearing all tracked entities from the context.
Note that this method does not generate StateChanged events since entities are not individually detached.
See EF Core change tracking for more information and examples.
DetectChanges()
Scans the tracked entity instances to detect any changes made to the instance data. DetectChanges()
is usually called automatically by the context when up-to-date information is required (before
SaveChanges() and when returning change tracking information). You typically only need to
call this method if you have disabled AutoDetectChangesEnabled.
See EF Core change tracking for more information and examples.
public virtual void DetectChanges()
Entries()
Returns an EntityEntry for each entity being tracked by the context. The entries provide access to change tracking information and operations for each entity.
public virtual IEnumerable<EntityEntry> Entries()
Returns
- IEnumerable<EntityEntry>
An entry for each entity being tracked.
Remarks
Consider using the methods of Local for faster lookup of tracked entities by key, foreign key, or property value.
This method calls DetectChanges() to ensure all entries returned reflect up-to-date state. Since detecting changes can be slow, consider temporarily setting AutoDetectChangesEnabled to prevent detecting changes in situations where the state is known to be up-to-date.
Note that modification of entity state while iterating over the returned enumeration may result in an InvalidOperationException indicating that the collection was modified while enumerating. To avoid this, create a defensive copy using ToList<TSource>(IEnumerable<TSource>) or similar before iterating.
See EF Core change tracking for more information and examples.
Entries<TEntity>()
Gets an EntityEntry for all entities of a given type being tracked by the context. The entries provide access to change tracking information and operations for each entity.
public virtual IEnumerable<EntityEntry<TEntity>> Entries<TEntity>() where TEntity : class
Returns
- IEnumerable<EntityEntry<TEntity>>
An entry for each entity of the given type that is being tracked.
Type Parameters
TEntity
The type of entities to get entries for.
Remarks
Consider using the methods of Local for faster lookup of tracked entities by key, foreign key, or property value.
This method calls DetectChanges() to ensure all entries returned reflect up-to-date state. Since detecting changes can be slow, consider temporarily setting AutoDetectChangesEnabled to prevent detecting changes in situations where the state is known to be up-to-date.
Note that modification of entity state while iterating over the returned enumeration may result in an InvalidOperationException indicating that the collection was modified while enumerating. To avoid this, create a defensive copy using ToList<TSource>(IEnumerable<TSource>) or similar before iterating.
See EF Core change tracking for more information and examples.
HasChanges()
Checks if any new, deleted, or changed entities are being tracked such that these changes will be sent to the database if SaveChanges() or SaveChangesAsync(CancellationToken) is called.
public virtual bool HasChanges()
Returns
Remarks
This method calls DetectChanges() to ensure the returned value is accurate. Since detecting changes can be slow, consider temporarily setting AutoDetectChangesEnabled to prevent detecting changes in situations where the state is known to be up-to-date.
See EF Core change tracking for more information and examples.
TrackGraph(object, Action<EntityEntryGraphNode>)
Begins tracking an entity and any entities that are reachable by traversing its navigation properties.
Traversal is recursive so the navigation properties of any discovered entities will also be scanned.
The specified callback
is called for each discovered entity and must set the
State that each entity should be tracked in. If no state is set, the entity
remains untracked.
public virtual void TrackGraph(object rootEntity, Action<EntityEntryGraphNode> callback)
Parameters
rootEntity
objectThe entity to begin traversal from.
callback
Action<EntityEntryGraphNode>An action to configure the change tracking information for each entity. For the entity to begin being tracked, the State must be set.
Remarks
This method is designed for use in disconnected scenarios where entities are retrieved using one instance of the context and then changes are saved using a different instance of the context. An example of this is a web service where one service call retrieves entities from the database and another service call persists any changes to the entities. Each service call uses a new instance of the context that is disposed when the call is complete.
If an entity is discovered that is already tracked by the context, that entity is not processed (and its navigation properties are not traversed).
See EF Core change tracking for more information and examples.
TrackGraph<TState>(object, TState, Func<EntityEntryGraphNode<TState>, bool>)
Begins tracking an entity and any entities that are reachable by traversing its navigation properties.
Traversal is recursive so the navigation properties of any discovered entities will also be scanned.
The specified callback
is called for each discovered entity and must set the
State that each entity should be tracked in. If no state is set, the entity
remains untracked.
public virtual void TrackGraph<TState>(object rootEntity, TState state, Func<EntityEntryGraphNode<TState>, bool> callback)
Parameters
rootEntity
objectThe entity to begin traversal from.
state
TStateAn arbitrary state object passed to the callback.
callback
Func<EntityEntryGraphNode<TState>, bool>An delegate to configure the change tracking information for each entity. The second parameter to the callback is the arbitrary state object passed above. Iteration of the graph will not continue down the graph if the callback returns false.
Type Parameters
TState
The type of the state object.
Remarks
This method is designed for use in disconnected scenarios where entities are retrieved using one instance of the context and then changes are saved using a different instance of the context. An example of this is a web service where one service call retrieves entities from the database and another service call persists any changes to the entities. Each service call uses a new instance of the context that is disposed when the call is complete.
Typically traversal of the graph should stop whenever an already tracked entity is encountered or when an entity is reached that should not be tracked. For this typical behavior, use the TrackGraph(object, Action<EntityEntryGraphNode>) overload. This overload, on the other hand, allows the callback to decide when traversal will end, but the onus is then on the caller to ensure that traversal will not enter an infinite loop.
See EF Core change tracking for more information and examples.
Events
DetectedAllChanges
An event fired when any changes have been detected to the entity graph, either through an explicit call to DetectChanges(), or automatically, such as part of executing SaveChanges() or SaveChangesAsync(CancellationToken).
public event EventHandler<DetectedChangesEventArgs> DetectedAllChanges
Event Type
Remarks
AutoDetectChangesEnabled is set to false for the duration of the event to prevent an infinite loop of recursive automatic calls.
See EF Core change tracking for more information and examples.
DetectedEntityChanges
An event fired when any changes have been detected to a single entity, either through an explicit call to DetectChanges() or DetectChanges(), or automatically, such as part of executing SaveChanges() or SaveChangesAsync(CancellationToken).
public event EventHandler<DetectedEntityChangesEventArgs> DetectedEntityChanges
Event Type
Remarks
AutoDetectChangesEnabled is set to false for the duration of the event to prevent an infinite loop of recursive automatic calls.
See EF Core change tracking for more information and examples.
DetectingAllChanges
An event fired when detecting changes to the entity graph about to happen, either through an explicit call to DetectChanges(), or automatically, such as part of executing SaveChanges() or SaveChangesAsync(CancellationToken).
public event EventHandler<DetectChangesEventArgs> DetectingAllChanges
Event Type
Remarks
AutoDetectChangesEnabled is set to false for the duration of the event to prevent an infinite loop of recursive automatic calls.
See EF Core change tracking for more information and examples.
DetectingEntityChanges
An event fired when detecting changes to a single entity is about to happen, either through an explicit call to DetectChanges() or DetectChanges(), or automatically, such as part of executing SaveChanges() or SaveChangesAsync(CancellationToken).
public event EventHandler<DetectEntityChangesEventArgs> DetectingEntityChanges
Event Type
Remarks
AutoDetectChangesEnabled is set to false for the duration of the event to prevent an infinite loop of recursive automatic calls.
See EF Core change tracking for more information and examples.
StateChanged
An event fired when an entity that is tracked by the associated DbContext has moved from one EntityState to another.
public event EventHandler<EntityStateChangedEventArgs> StateChanged
Event Type
Remarks
Note that this event does not fire for entities when they are first tracked by the context. Use the Tracked event to get notified when the context begins tracking an entity.
See EF Core change tracking for more information and examples.
StateChanging
An event fired when an entity that is tracked by the associated DbContext is moving from one EntityState to another.
public event EventHandler<EntityStateChangingEventArgs> StateChanging
Event Type
Remarks
Note that this event does not fire for entities when they are first tracked by the context. Use the Tracking event to get notified when the context begins tracking an entity.
See EF Core change tracking for more information and examples.
Tracked
An event fired when an entity is tracked by the context, either because it was returned from a tracking query, or because it was attached or added to the context.
public event EventHandler<EntityTrackedEventArgs> Tracked
Event Type
Remarks
See EF Core change tracking for more information and examples.
Tracking
An event fired when an entity is about to be tracked by the context, either because it is returned from a tracking query, or because it is being attached or added to the context.
public event EventHandler<EntityTrackingEventArgs> Tracking
Event Type
Remarks
See EF Core change tracking for more information and examples.