In the Entity Framework, every time we read one or more records of data from the database, they are tracked by ChangeTracker by default. And that gives us some performance reduction. If we do not want the Entity Framework to perform this entity tracking operation, we can use AsNoTracking when reading data. For example, in the following code, I get a list of all users and they are not tracked by ChangeTracker

var users = await _dbContext.Users.AsNoTracking().ToListAsync();

There is no problem in this case and it has a good performance. But what if we want to get the role of each user along with each user? We can use Include.

For example, we should do the following:

var users = await _dbContext.Users.AsNoTracking()
                       .Include(a => a.Role).ToListAsync();

In this case, because the Entity Framework does not track entities, it creates a new entity for each user to role each user, which creates additional entities. That is, it creates a role for each user that several users may have a common role with, while a Role entity can be used for multiple users.

But in Entity Framework Core 5, a new method called AsNoTrackingWithIdentityResoluyion has been added, which is a combination of AsNoTracking and Tracking. Which solves the previous problem. That is, it receives data in the form of AsNoTracking that is not traceable, and also all users who have a common role point to an entity, not each user has its own entity.

This method can be used as follows:

var users = await _dbContext.Users.AsNoTrackingWithIdentityResolution()
                       .Include(a => a.Role).ToListAsync();

:)

Powered by Froala Editor

Comments