liveBook · Manning

AsNoTracking

As explained in .NET in Action, Second Edition

AsNoTracking is an Entity Framework Core query extension method that prevents returned entities from being tracked by the context.

AsNoTracking is an Entity Framework Core query extension method for read-only results. It prevents returned entities from entering the DbContext change tracker, reducing memory and CPU use and limiting accidental updates. section 5.4.1

Read-only books endpoint

A CatalogController applies AsNoTracking after including related ratings: _dbContext.Books.Include(b => b.Ratings).AsNoTracking(). Because the GetBooks endpoint only returns Book objects, changes to a returned Title are not recorded for a later SaveChanges call. section 5.4.1

Listing 5.25 Adding a new controller that allows requesting a list of books
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
  
namespace ManningBooksApi.Controllers;                 #1
  
[ApiController]                                        #2
[Route("[controller]")]                                #3
public class CatalogController : ControllerBase
{
  private readonly CatalogContext _dbContext;          #4
  
  public CatalogController(
    CatalogContext dbContext)                          #5
  {
    _dbContext = dbContext;
  }
  
  [HttpGet]                                            #6
  public IAsyncEnumerable<Book> GetBooks(              #7
      string? titleFilter = null)                      #8
  {
    IQueryable<Book> query = _dbContext.Books          #9
      .Include(b => b.Ratings)
      .AsNoTracking();                                 #10
    if (titleFilter != null)
    {
      query = query.Where(b =>
        b.Title.ToLower().Contains(titleFilter.ToLower()));
    }
  
    return query.AsAsyncEnumerable();                  #11
  }
}

Inspect the controller listing to see AsNoTracking placed in the IQueryable pipeline before optional filtering and asynchronous enumeration. section 5.4.1

How .NET in Action, Second Edition covers it

How deep it goes
Explains query-level behavior, memory and CPU effects, and accidental updates without descending into tracking internals.
Examples
Uses a GetBooks endpoint returning Book objects and including related ratings.
What it assumes
Assumes familiarity with EF Core queries and DbContext while defining change tracking through a Book update example.
What you can do after
Apply it via Entity Framework Core to optimize read-only queries and avoid tracking unintended changes.
How it connects
Connects Entity Framework Core queries with DbContext, change tracking, SaveChanges, and ASP.NET Core controllers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.