Wednesday, August 11, 2021

Entity Tracking in Entity Framework

Tracking is the feature of EF used to track changes in entities. 

If entities are changed, the changes are persisted to database during SaveChanges(), because those changes are tracked by EF.

Remember that Keyless entities are never tracked. 

Any query that returns an entity type is a tracking query. By default any query returning entity is called a tracking query and it is tracked. 

Even if a query anonymously returns an entity type, EF detects is and tracks the entity. 


To disable tracking on an entity returning query, use AsNoTracking()

    context.Blogs.AsNoTracking().ToList();

This behaviour can also be changed at context level: 

    context.ChangeTracker.QueryTrackingBehaviour = QueryTrackingBehaviour.NoTracking;


Identity Resolution: EF keeps track of tracked entities using the identity. It always maintains a single instance of tracked entities and returns the same instance when demanded, without hitting database. Thus when an entity is asked for, EF first checks whether entity with that identity already exists in context and returns the same if exists. This checking is done purely on the basis of identity property of the entity. 

This feature is called Identity resolution.

Non-tracking queries are not tracked, hence identity resolution is not done for them. Every time a no-tracking query is called, it results in a database hit. 


Now in EF5.0, we can have a non-tracking query with identity resolution. You need to use AsNoTrackingWithIdentityResolution() method for that. 

This creates a separate stand-alone tracker for this query and tracks it. After the query is enumerated fully, this stand-alone tracker goes out of scope and is garbage-collected. The context is not aware of this stand-alone tracking. 


What happens to tracking when the query contains a mix of tracked and keyless entities ?

From EF3.0 onwards, keyed entities in such mixed queries ARE tracked and keyless entities

are not tracked. 

Prior to EF3.0, the entire query results were untracked.

No comments:

Post a Comment

 using Microsoft.AspNetCore.Mvc; using System.Xml.Linq; using System.Xml.XPath; //<table class="common-table medium js-table js-stre...