Understanding Entity Frameworks AsNoTracking

Entity Frameworks AsNoTracking
0 68

Get real time updates directly on you device, subscribe now.

2 min read

If you are working on a .NET project and have used Entity Framework to connect to the Database, then you must have encountered the AsNoTracking() method if not then this journal entry is going to help you in understanding the same.

The DbContext of Entity Framework takes care of tracking the changes done in the objects and correctly updates the database when the SaveChanges() method is called. In other words we can say that, whenever we retrieve entities using an object query, the Entity Framework puts those in cache and tracks the changes made on them until we call the SaveChanges() method.

In some scenarios, we just want the data from the entities and do want them to be tracked. These are the scenarios where we just want to display the data or lets say we want the data just for viewing purpose and other operations like Insert, Update, and Delete operations are not performed on that data. In the scenarios like these, we can use the AsNoTracking() extension method. This extension method when used with the DbContext object will return a new query and the returned entities will not be cached. This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query. However, if you need these entities to be updated then you can do that by attaching it to the context.


dbContext.TableName.Attach(updatedObject);

After attaching the entity you can simply call the SaveChanges() method to save the updated changes in the entities.


dbContext.SaveChanges();

How to use AsNoTracking

The namespace “System.Data.Entity” contains this extension and it is very easy to use in our applications. The following is an example of how to use the AsNoTracking method.

The first query returns all the data from the database table and we have applied the AsNoTracking() method on the DbContext object. The second query returns all the rows with an Age greater than or equal to 18 and here we apply the AsNoTracking() method on the IQueryable object.


using(ApplicationDbContext db = new ApplicationDbContext()) {

var list = db.TableEntityName.AsNoTracking().ToList();

var list2 = db.TableEntityName.Where(x > x.Age >= 18).AsNoTracking().ToList();

}

 

AsNoTracking Query Performance and When to Use

The AsNoTracking() method can save both memory usage and execution times as we are not caching the data. Applying this option really becomes important when we retrieve a large amount of data from the database which will be used just for viewing purpose and don’t intend to save the data back to the database.