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
