What is the use of AsNoTracking() in EF Core?

AsNoTracking() flags the framework to not to track changes on the records returned. EF Core then doesn't persist the result, thus conserving memory.

When querying for records from an EntitySet using Entity Framework Core, it persists the state of the records returned and keeps track of any changes that are applied on the records.

AsNoTracking() is an extension method that flags the framework to not to track changes on the records returned.

Entity Framework Core then doesn’t persist the result, thus conserving memory.

Example –

var result = _db.MyEntities.AsNoTracking()
.Where(x => x.IsActive == true).First();

// result returned now is not tracked and 
// so whatever changes are applied, can't be saved

When to use?

It is useful for cases involving read-only queries where no data is overwritten via the records. Use it when you don’t require the entities returned by your query need to be tracked and updated back to database.

Sriram Mannava
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply

Your email address will not be published. Required fields are marked *