As we know, when we using AsNoTracking
, the change tracker does not track the entity’s changes.
But when updating an entity which was fetched with AsNoTracking
, EF Core tracks this entity’s properties automatically (when calling SaveChanges()
).
So why don’t we always use AsNoTracking
in EF Core based on this behavior?
2
Answers
AsNoTracking() is useful when you know you don’t need change tracking. But using it all the time means losing a lot of EF Core’s benefits like automatic change detection, concurrency handling, identity resolution, caching and performance ( performance – Tracking entity changes has performance costs, so if you don’t need change tracking, using AsNoTracking() can improve performance by avoiding that overhead. However, if you do need change tracking for an entity, using AsNoTracking() will actually hurt performance because EF will have to recreate the change tracking infrastructure when you save changes) . You end up having to re-implement some of that manually.
Tracking vs. No-Tracking Queries
You have misunderstood one thing. When you use
AsNoTracking()
to fetch data , then directSaveChanges()
wont track the entity’s properties automatically. you have to manually call theUpdate()
method to mark the entity as modified. so EF will track entity’s properties and then have to useSaveChanges()
method updates the corresponding row in the database.Here are some scenarios where you might want to use tracking.
features, such as automatic detection of modified entities.
is not a concern.
On the other hand, here are some scenarios where you might want to use no tracking.
do not plan to update them.
is a concern.