Friday, April 3, 2020

Tracking vs No-Tracking queries

Entities retrieved using Entity Framework Core LINQ queries have tracking enabled by default, this allows us to make changes to the entity and save them back to the database using SaveChanges.

Tracking can be disabled at a query level by adding AsNoTracking extension method to the query. For queries which retrieve large amount of read-only data it is recommended to disable tracking to improve performance. Disabling tracking helps us to gain some performance and also save on memory since we don’t have to save tracking information in the cache.

To disable tracking at the context level we need to set NoTracking to the QueryTrackingBehavior property as follows.
using (UserRegistrationContext _context = new UserRegistrationContext ())

    _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 
    ... 
    ... 
}

Tracking will not be performed when the query result does not contain an entity type i.e when we make an anonymous / custom object from a query it is not tracked and applying SaveChanges does not save changes to the object to the database. The below code snippet will execute without any exceptions but the changes will not get saved to the database.

    var employee = _context.Employee
                    .Where(e => e.EmployeeId == 1)
                    .Select(e => new EmployeeDetail
                    {
                        EmployeeId = e.EmployeeId,
                        Department = e.Department.Name,
                        Name = e.Name,
                        Age = e.Age,
                        Country = e.Country.Name
                    }).FirstOrDefault();

    employee.Name = "Tim1";
    employee.Age = 35;

    _context.SaveChanges();


Search Flipkart Products:
Flipkart.com

No comments: