entity-framework-corechange-tracking

Clarification on behaviour of QueryTrackingBehavior property of ChangeTracker (EF Core)


Please help with clarification on behaviour of EF Core when QueryTrackingBehavior property of ChangeTracker is changed.

Let say up to this point in the code, we have everything at default (which means all queries are tracked). Some data has been read/updated and tracked.

Now we update QueryTrackingBehavior property of ChangeTracker to NoTracking. Does this "reset" the tracking of the entities that were read previously?

Let's say we read additional data (not tracked now).

If we change QueryTrackingBehavior property of ChangeTracker back to TrackAll, do the entities read prior of the change retain their tracking so that SaveChanges() performs the right updates, ignoring anything that was read while the ChangeTracker was set to NoTracking?


Solution

  • Setting QueryTrackingBehavior only affects queries that run subsequently and modifying this property doesn't affect the states of tracked entities.

    This can be checked by listing the entities in the change tracker, for example:

    context.Products.Find(1);
    
    context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
    
    context.Products.Find(2);
    context.Products.Add(new Product { Id = 21 });
    
    context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.TrackAll;
    
    context.Products.Find(3);
    
    var ids = context.ChangeTracker.Entries()
        .Select(e => ((Product)e.Entity).Id).ToList();
    

    The result is:

    21
    1
    3
    

    As you see, Product 2 isn't tracked, while entities can still be attached to the change tracker when QueryTrackingBehavior is set to NoTracking, hence the name "query tracking behavior".