wasAsked.

What is .AsNoTracking()?

Impetus · Role not specified · technical

Published

Year not specified · Entity Framework Core

Community answers

Posted by wasAsked editorial collection

AsNoTracking() tells Entity Framework Core not to track the entities returned by a query in the change tracker. By default (tracking queries) - EF Core stores each returned entity in the DbContext's change tracker with a snapshot of its original values. - When you modify the entity and call SaveChanges(), EF detects the changes and generates UPDATE statements. - Identity resolution: if the same row appears twice, you get the same object instance. With AsNoTracking var products = await db.Products .AsNoTracking() .Where(p => p.IsActive) .OrderBy(p => p.Name) .ToListAsync(ct); - Entities are not stored in the change tracker, and no snapshots are kept. - Faster materialisation and lower memory use, especially for large result sets. - Changes made to these objects are not saved by SaveChanges (unless you attach them explicitly). When to use it - Read-only scenarios: API GET endpoints, reports, dashboards, lists, exports. - Large queries where tracking overhead is noticeable. When not to use it - When you load entities in order to modify and save them in the same context. Related options - AsNoTrackingWithIdentityResolution(): no tracking, but still returns the same instance for duplicate rows (useful with Includes that would otherwise duplicate related entities). - Make no-tracking the default for a context: optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) — then use AsTracking() when you need tracking. - Projections: queries that select into DTOs (Select(p => new ProductDto(...))) are not tracked anyway, because they do not return entity types. Projection is often even better than AsNoTracking, since it reads only the needed columns. Updating untracked entities If you have a detached entity (for example from an API request), you can attach it and mark it modified (db.Update(entity)), but this updates all columns; loading the tracked entity and changing specific properties is usually safer. Interview summary: "AsNoTracking skips change tracking, which makes read-only queries faster and lighter. I use it for all read-only queries or rely on projections, and use tracking only when I intend to update the loaded entities."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics