skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. You have misunderstood one thing. When you use AsNoTracking() to fetch data , then direct SaveChanges() wont track the entity’s properties automatically. you have to manually call the Update() method to mark the entity as modified. so EF will track entity’s properties and then have to use SaveChanges() method updates the corresponding row in the database.

    Here are some scenarios where you might want to use tracking.

    1. When you need to update entities frequently and efficiently.
    2. When you want to take advantage of EF Core’s change tracking
      features, such as automatic detection of modified entities.
    3. When you have a small number of entities in memory and memory usage
      is not a concern.

    On the other hand, here are some scenarios where you might want to use no tracking.

    1. When you only need to retrieve entities for read-only purposes and
      do not plan to update them.
    2. When you have a large number of entities in memory and memory usage
      is a concern.
    3. When you are querying many entities and performance is a concern.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search