Friday, April 3, 2020

No-tracking queries in Entity Framework Core

Entities retrieved using Entity Framework Core have tracking enabled by default, however there are some situations in which we will not need tracking. Let us say we need to load a Grid in the UI with a large amount of data which will not be updated in this case we will not need tracking since the data is read-only.
To fetch entity data without tracking we need to add the AsNoTracking extension method to the query. When we add AsNoTracking to the query Entity Framework does not track changes to the object.

If we make changes to an entity which was retrieved using a query with AsNoTracking and later use SaveChanges, then the changes to the entity will not be saved to the database. Let us takes the same example from the previous post, except that we will add AsNoTracking extension method to the query.

      var employee = _context.Employee
                      .Where(e => e.EmployeeId == 1)
                      .AsNoTracking()
                      .FirstOrDefault<Employee>();

      employee.Age = 40;
      employee.City = "Los Angels";
      employee.State = "CA";

      _context.SaveChanges();

 Now the changes made to the employee entity object will not be saved to the database even after calling SaveChanges, this is because we have the AsNoTracking method to the query.

Adding AsNoTracking disables tracking only for the query to which it is added, if we want to disable tracking for a set of queries using a context object, we can do this by setting the property as follows.

using (UserRegistrationContext _context = new UserRegistrationContext ()) 
{ 
    _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 
    ... 
    ... 
}


Search Flipkart Products:
Flipkart.com

No comments: