concept asnotracking method in category entity framework

This is an excerpt from Manning's book Entity Framework Core in Action.
Listing 2.15 highlights in bold the
AsNoTracking
method. This stops EF Core from taking a tracking snapshot (see figure 1.6), which makes the query slightly quicker. You should use theAsNoTracking
method in any read-only queries (queries in which you only read the data, but don’t ever update the data).
Figure 9.5 The default way that EF Core finds whether anything has been changed. EF Core holds a tracking snapshot of any entities loaded as tracked entities—any query that doesn’t include the
AsNoTracking
method. WhenSaveChanges
is called, EF Core, by default, runs theDetectChanges
method, which compares tracked entities with the tracking snapshot and sets theState
of the entities that have been modified toModified
.![]()
Always adding the AsNoTracking
method to read-only queries
12.4.4 Always adding the AsNoTracking method to read-only queries
If you’re reading in entity classes directly and you aren’t going to update them, including the
AsNoTracking
method in your query is worthwhile. It tells EF Core not to create a tracking snapshot of the entities loaded, which saves a bit of time and memory usage. This is an example of a query in which theAsNoTracking
method, in bold, will improve performance.Listing 12.4 Using the
AsNoTracking
method to improve the performance of a queryvar result = context.Books #1 .Include(r => r.Reviews) #1 .AsNoTracking() #2 .ToList(); #1 Returns a Book entity class and a collection of Review entity classes. #2 Adding the AsNoTracking method tells EF Core not to create a tracking snapshot, which saves time and memory usage. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":2,\"ch\":4},{\"line\":2,\"ch\":19}]]"} !@%STYLE%@!