concept asnotracking method in category entity framework

appears as: AsNoTracking method
Entity Framework Core in Action

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 the AsNoTracking 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. When SaveChanges is called, EF Core, by default, runs the DetectChanges method, which compares tracked entities with the tracking snapshot and sets the State of the entities that have been modified to Modified.

c09_05.png
  • 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 the AsNoTracking method, in bold, will improve performance.

    Listing 12.4 Using the AsNoTracking method to improve the performance of a query
    var 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%@!

    If you use a Select query in which the result maps to a DTO, and that DTO doesn’t contain any entity classes, you don’t need to add the AsNoTracking method. But if your DTO contains an entity class inside it, adding the AsNoTracking method will help.

    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest