Middle
What is tracking in Entity Framework?
sobes.tech AI
Answer from AI
Tracking (Entity Tracking) is a mechanism in Entity Framework Core that monitors changes made to entity objects loaded from the database. The Context stores information about the state of each loaded entity and can generate SQL queries for the corresponding database update when saving changes (DbContext.SaveChanges()).
Main entity states:
- Added: The entity has been added to the context but does not yet exist in the database.
- Unchanged: The entity was loaded from the database, and its properties have not been modified.
- Modified: Some properties of the entity have been changed since it was loaded from the database.
- Deleted: The entity has been marked for deletion from the database.
- Detached: The entity is not being tracked by the context.
By default, entities are tracked when working with LINQ queries. This allows Entity Framework to automatically determine which changes need to be saved.
Example of explicit tracking:
// Tracked query
var trackedUser = context.Users.FirstOrDefault(u => u.Id == 1);
// Untracked query
var untrackedUser = context.Users.AsNoTracking().FirstOrDefault(u => u.Id == 2);
Disabling tracking with AsNoTracking() can improve performance when executing queries if you do not need to save changes to the database, as EF does not spend resources tracking entity states.