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

