Entity Framework Core 2.1: Using NoTracking (better performance)

We know that one way to update a record using the Entity Framework is to query that record, update some of its values, and then use the SaveChanges function to save the changes in the database. The reason why we can do this is because by default, when we bring database records using EF, it keeps track of any changes that occur in any of the properties of objects created with the query. Certainly, this functionality has a cost in terms of application performance. If you know that you are not going to make changes to the objects immediately, then you have the opportunity to turn off this “tracking” that EF Core does on the objects. For this we use the AsNoTracking function.

The AsNoTracking function serves to prevent EF Core from tracking changes made to objects that were created from a query. This will make your application run queries faster. Let’s see an example:

using (var context = new ApplicationDbContext())
   var students = context.Students.AsNoTracking().ToList();

With this, this list of records is not being tracked by EF Core, which implies that, if we edit any of its properties, and then do SaveChanges, the changes will not be made in the database.

If in a context you are going to make several queries, and you want every one to use AsNoTracking automatically, then you can change the behavior of the change tracker globally:

using (var context = new ApplicationDbContext())
   context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
   var students = context.Students.ToList();
   var course = context.Courses.FirstOrDefault();

Whenever there is an entity as a result of a query, by default, this will be applied to the tracking unless you use some of the previous methods to avoid it. If you use a select to generate something that is not an entity, then EF Core will not apply the tracking functionality automatically, in this sense, the AsNoTracking function is not necessary to be used:

using (var context = new ApplicationDbContext())
   // Will not be tracked
   var studentsIds = context.Students.Select(x => x.Id).ToList();
   var studentsBasicData = context.Students.Select(x => new { x.Id, x.Name }).ToList();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s