a blog for those who code

Thursday 9 March 2017

Why you should use AsNoTracking in Entity Framework

In this post we will be discussing about Tracking vs No-Tracking in Entity Framework. Tracking the entities in the context is useful when you want to change anything in that entity. But Sometimes you only want to query the entities and wants it to be queried fast. Thus No-Tracking comes into picture which will ensure minimal memory usage and optimal performance.

What is No-Tracking Queries

No-Tracking queries allows you to tell Entity Framework not to track the results of a query. That means Entity Framework performs no additional processing or storage of the entities which are returned by the query. Thus it also means that you cannot update these entities without reattaching them to the tracking graph.

How to use No-Tracking

Using No-Tracking is relatively simple and easy. Add using System.Data.Entity if its not added already and then include .AsNoTracking() on your query as shown below

var user = dbContext.Users.AsNoTracking()
   .Where(user => user.UserId == userid)
return user;

When we use function AsNoTracking() on the query we are explicitly telling Entity Framework that the entities are not tracked by the context. If you want to make changes to un-tracked entities you must remember to attach them before calling SaveChanges.


Does Anonymous Type are Tracked ?

If the anonymous type has the instance of entity types they will be tracked by default. That means the below anonymous types are tracked

var user = dbcontext.Users.Select(u = > new 
      User = u,
      Employee = u.Employee

But if the result set does not contain any entity type, no tracking is performs as shown below :

var user = dbcontext.Users.Select(u = > new 
        UserID = u.UserId,
        FirstName = u.FirstName,
        LastName = u.LastName

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

1 comment: