Entity Framework will keeps track of any changes made to entities being tracked by a context. It is the responsibility of the Change Tracker to keep track of these changes.
The Change Tracker API gives access to additional operations that can be performed on an entity.
Entity Framework keeps track of the changes made to entity objects. For this it uses the change tracker. It can be accessed through the DbContext.ChangeTracker property.
Change tracking is used to:
- Update the state of every entity object so that changes can be persisted to the database; and
- Performs relationship fix-up when combination of reference navigation properties, collection navigation properties and foreign keys exists
How it works
There are two different ways that Entity Framework can track the changes in the model objects:
- Snapshot change tracking. Entity Framework detect changes using a snapshot-based mechanism:
- It works with pure POCO classes which don’t contain any bult-in logic to notify Entity Framework of any changes in the entity data (i.e. class properties);
- A snapshot of the content of the objects occurs when these are returned from the database and registered on the DbContext (i.e. materialized);
- A snapshot of the content of the objects occurs when these are added to the DbContext.
- Change tracking proxies. Entity Framework tracks changes using an automatic notification-based mechanism:
- It works with dynamic proxy objects created at runtime derivated from the POCO classes;
- Entity Framework is notified of any change occurred due to a communication mechanism implemented in the proxy properties.
Tracking State of an Entity
|Added||The entity is being tracked by a DbContext but does not exist in the database. During SaveChanges an
|Unchanged||The entity is being tracked by a DbContext and has not been modified since it was retrieved from the database. SaveChanges will not need process the entity.|
|Modified||The entity is being tracked by a DbContext and has been modified in memory since it was retrieved from the database. During SaveChanges an
|Deleted||The entity is being tracked by a DbContext and has been marked for deletion. During SaveChanges a
|Detached||The entity is not being tracked by the DbContext.Setting the entity state as Detached clears out all the references to the context and also clears the navigation properties of the entity.|
Working with Change Tracker API
Refer to the following articles for details of the Change Tracker API:
- Change Tracker: Working with tracking information (Single Entity)
- Change Tracker: Working with individual properties (Single Entity)
- Change Tracker: Working with tracking information (Multiple Entities)