liveBook · Manning

Change tracking

As explained in .NET in Action, Second Edition

Change tracking is an ORM capability that records changes to entity instances so they can be persisted to a data store.

Change tracking is an Entity Framework Core capability that records what happens to entity instances returned from queries or added to a DbContext. Modify a Book.Title property, then call SaveChanges; EF Core converts the recorded change into an UPDATE SQL statement. section 5.4.1

Use tracking deliberately in request handlers:

  • Keep the default when queried entities may be modified and persisted. section 5.4.1
  • Call AsNoTracking for read-only queries such as a GET endpoint; this prevents accidental changes and saves memory and CPU. 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 a controller that applies AsNoTracking to a read-only Book query. section 5.4.1

How .NET in Action, Second Edition covers it

How deep it goes
Explains default tracking, property-change detection, SaveChanges translation, and query-level disabling, without detailing tracking internals.
Examples
Uses a Book title modification and a read-only CatalogController GET query with AsNoTracking.
What it assumes
Assumes familiarity with entities, DbContext queries, property modification, and SaveChanges.
What you can do after
Apply it via Entity Framework Core to persist edits or optimize read-only queries.
How it connects
Connects Entity Framework Core, DbContext, entities, queries, SaveChanges, and SQL UPDATE statements.

Also explained in

Compare how 2 books explain change tracking →

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.