AsNoTracking is an Entity Framework Core query option that returns entities without registering them in the DbContext's change tracker. Background: change tracking Normally, when EF Core loads entities, it keeps them in the change tracker along with a snapshot of their original values. That allows SaveChanges to detect what changed and generate UPDATE statements. Tracking costs CPU and memory, especially for large result sets. Using AsNoTracking var orders = await _db.Orders .AsNoTracking() .Where(o => o.CustomerId == customerId) .OrderByDescending(o => o.CreatedAt) .Take(50) .ToListAsync(ct); Effects - Faster queries and less memory, because EF skips snapshotting and tracking. - The DbContext does not hold references to these objects, so they can be garbage-collected sooner. - Modifying these objects and calling SaveChanges does nothing, since EF is not tracking them. - Duplicate rows produce separate object instances (no identity resolution), unless you use AsNoTrackingWithIdentityResolution(). When to use it - Read-only operations: GET endpoints, search results, reports, dropdown data, exports, background jobs that only read. When not to use it - Load-modify-save workflows in the same context: var order = await _db.Orders.FirstAsync(o => o.Id == id, ct); // tracked order.Status = OrderStatus.Shipped; await _db.SaveChangesAsync(ct); // UPDATE generated Configuring a default You can make no-tracking the default for a context: options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); and then call AsTracking() explicitly when you need to update. This works well for read-heavy services, or with a separate read-only context in CQRS-style designs. A related best practice For API responses, projecting to DTOs with Select is often even better: projections are not tracked anyway, and they read only the columns you need. var list = await _db.Orders.Where(...).Select(o => new OrderSummary(o.Id, o.Total)).ToListAsync(ct);
Ravindra Wadile · · 0 likes