Tracking vs. No-Tracking Queries in EF


Tracking vs. No-Tracking Queries in EF

Tracking behavior controls if Entity Framework Core will keep information about an entity instance in its change tracker. If an entity is tracked, any changes detected in the entity will be persisted in the database during SaveChanges(). EF Core will also fix up navigation properties between the entities in a tracking query result and the entities in the change tracker.

Tracking queries

By default, queries that return entity types are tracked. This means you can make changes to those entity instances and have those changes persisted by SaveChanges(). In the following example, the blog rating transition will be detected and persisted in the database during SaveChanges().

When the results are returned in a tracking query, EF Core will check if the entity is already in the context. If EF Core finds an existing entity, the same instance is returned. EF Core won't overwrite current and original values of the entity's properties in the entry with the database values. If the entity isn't found in the context, EF Core will create a new entity instance and attach it to it. Query results don't contain any entity added to the context but are not yet saved to the database.

No-tracking queries

No tracking queries are helpful when the results are used in a read-only scenario. They're quicker to execute because there's no need to set up the change tracking information. A no-tracking query should be used if you don't need to update the entities retrieved from the database. You can swap a particular question to be no-tracking. No tracking query will also give you results based on what is in the database disregarding any local changes or added entities.

Identity resolution

Since a tracking query uses the change tracker, EF Core will make identity resolution in a tracking query. When materializing an entity, EF Core will return the same entity instance from the change tracker if it's already being tracked. If the result contains the same entity multiple times, you get back the same instance for each occurrence. No-tracking queries don't use the change tracker and don't make identity resolution. So you get back a new instance of the entity even when the same entity is contained in the result multiple times.

Tracking and custom projections

Even if the result type of the query isn't an entity type, EF Core will still track entity types contained in the result by default. In the following query, which returns an anonymous type, Blog instances in the result set will be tracked.