skip to content

In EF Core 10, how do AsNoTracking, AsNoTrackingWithIdentityResolution and QueryTrackingBehavior.NoTracking differ from a default tracking query?

level: middleimportance: should knowfreq 58%

answer

  1. TrackAll is the default
  2. no snapshot, no identity resolution
  3. stand-alone change tracker per query
  4. UseQueryTrackingBehavior and AsTracking
  5. projections without entities are untracked

basics

~20 s

A default query tracks results: one instance per key, snapshots, saved on SaveChanges. AsNoTracking tracks nothing and returns a new instance per row; AsNoTrackingWithIdentityResolution de-duplicates per query but still leaves results untracked; QueryTrackingBehavior changes the default for a context.

solid answer

~40 s

Queries default to `QueryTrackingBehavior.TrackAll`: each entity is attached `Unchanged`, snapshotted, de-duplicated against what the context already tracks (an already-tracked instance comes back with its local edits intact) and saved by `SaveChanges` if you edit it. `AsNoTracking()` skips all of that: results are plain objects, the same row appearing twice yields two instances, and edits are never saved unless you `Attach` or `Update` them. `AsNoTrackingWithIdentityResolution()` uses a stand-alone change tracker for the duration of the query, so each key is materialized once, but nothing is left in the context's tracker. To flip the default, call `UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)` in the options or set `ChangeTracker.QueryTrackingBehavior` on one instance, and opt single queries back in with `AsTracking()`.

code

csharp · 11 lines
csharp
builder.Services.AddDbContext<CrmDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("Crm"))
           .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));

// read endpoint: untracked by default
var list = await db.Customers.Where(c => c.Region == region).ToListAsync();

// write endpoint: opt back in for this query
var customer = await db.Customers.AsTracking().SingleAsync(c => c.Id == id);
customer.Phone = phone;
await db.SaveChangesAsync();

go deeper

for a junior

Use AsNoTracking for read-only queries and remember that its results are not saved by SaveChanges.

for a middle

Explain identity resolution in tracking queries, what AsNoTrackingWithIdentityResolution adds, and the two places a context's default tracking behaviour can be changed.

for a senior

Choose a default per context from the endpoint mix, catch handlers that edit untracked results, and know that a tracking query returns local edits rather than database values.

for a principal

Decide whether a codebase's read paths should default to no-tracking or projections, and how write paths make tracking explicit so reviewers can see it.

## Tracking is the default A **tracking query** is a LINQ query whose entity results are registered with the context's change tracker. EF Core 10 defaults to `QueryTrackingBehavior.TrackAll`. For every entity with a key that a tracking query materializes, EF Core: - looks the key up in the change tracker and, if an instance is already tracked, **returns that instance** without overwriting its current or original values - so unsaved local edits survive the query; - otherwise creates the object, attaches it as `Unchanged` and stores a **snapshot** of its values for later change detection; - fixes up navigations between the new results and entities it already tracks. Anything you then edit is written by the next `SaveChanges`. Keyless entity types are never tracked. ## The three ways to stop tracking | Mechanism | Scope | Results tracked by the context | Same row twice in one result | |---|---|---|---| | default (`TrackAll`) | every query | yes | one shared instance | | `AsNoTracking()` | one query | no | a new instance each time | | `AsNoTrackingWithIdentityResolution()` | one query | no | one instance per key within the query | | `QueryTrackingBehavior.NoTracking` as the default | every query of the context | no | a new instance each time | ### AsNoTracking `AsNoTracking()` returns objects the context knows nothing about. There is no snapshot and no identity resolution, so `db.Orders.AsNoTracking().Include(o => o.Customer)` over 50 orders of one customer materializes **50 `Customer` objects**. A no-tracking query also reads purely from the database: it ignores entities that are added or edited locally but not yet saved. Editing a result and calling `SaveChanges` does nothing, because the context never saw it. ### AsNoTrackingWithIdentityResolution `AsNoTrackingWithIdentityResolution()` (and the matching enum value `NoTrackingWithIdentityResolution`) creates a **stand-alone change tracker** for the duration of the query, so each key is materialized once and shared across the result graph. When enumeration finishes, that tracker goes out of scope; the context's own tracker never sees the results. Use it when a read-only result graph must not contain duplicates - for example when serializing a graph whose shape relies on reference equality. ### Changing the default 1. **For every instance of a context type:** `options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)` on `DbContextOptionsBuilder`, typically inside `AddDbContext`. 2. **For one context instance:** `db.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking`. 3. **For one query in a no-tracking context:** `AsTracking()` turns tracking back on for that query. A common split is a no-tracking default for read-heavy endpoints, with `AsTracking()` in the handful of handlers that load, modify and save. ## Projections Tracking applies to **entity instances**, not to query shapes. `db.Customers.Select(c => new { c, c.Orders.Count })` still tracks the `Customer` instances inside the anonymous type. A projection that contains no entity instance at all - `Select(c => new CustomerSummary(c.Id, c.Name))` - tracks nothing, whatever the tracking behaviour, because there is no entity to track. ## A version note Since EF Core 9 (and so in 10), `AsNoTrackingWithIdentityResolution` is restricted for JSON-mapped entity collections: applying operators such as `OrderBy`, `Where`, `Skip` or `Take` directly to a JSON collection navigation in such a query throws, and EF Core also throws when materialization order could corrupt the results. The documented mitigations are a tracking query when identity resolution is needed, or plain `AsNoTracking` when it is not. ## Mistakes to avoid - Loading with `AsNoTracking`, editing the result and expecting `SaveChanges` to persist it. - Assuming `AsNoTrackingWithIdentityResolution` adds the results to the context. - Assuming `AsNoTracking` is always cheaper: a large graph with many repeated references can produce more objects than a tracking query would. How no-tracking pays off at scale is a performance-tuning question in its own right. - Forgetting that a tracking query returns the already-tracked instance with its local edits, not fresh database values.

  • You load a Customer with AsNoTracking, change its email and call SaveChanges. What happens, and how would you make it save?
    Nothing is written: the context never tracked the object, so there is no entry to detect a change on. Either query with tracking in the first place, or call `db.Customers.Update(customer)` (all columns) or `Attach` plus `IsModified` for the email before `SaveChanges`.
  • If a context already tracks customer 42 with an unsaved phone edit, what does a tracking query for customer 42 return?
    The same tracked instance, with the unsaved phone value. EF Core does not overwrite current or original values of an entity it already tracks. A no-tracking query, by contrast, returns a new object with the database values. `Reload` on the entry is the explicit way to refresh a tracked entity from the database.

  • Editing an entity loaded with AsNoTracking and calling SaveChanges updates the row.
  • AsNoTrackingWithIdentityResolution adds its results to the context's change tracker.
  • AsNoTracking returns one shared instance for a row repeated across Include results.
  • A Select into a DTO with no entity inside is still tracked by default.
  • A tracking query always refreshes an already-tracked entity with database values.

Assumes EF Core 10; the restriction on AsNoTrackingWithIdentityResolution with JSON collection navigations has applied since EF Core 9.