Covers EF Core tracking versus no-tracking queries, identity resolution, snapshot and identity-map costs, QueryTrackingBehavior defaults, and when to choose tracking, AsNoTracking or AsNoTrackingWithIdentityResolution.
A tracking query (the default) adds every entity to the change tracker: EF Core keeps an identity map (one instance per key) and a snapshot of original values, so SaveChanges can detect edits. That costs memory and time.
AsNoTracking() skips both: fastest and leanest, but if the same row appears twice (e.g. the same customer on many orders via Include), you get separate instances.AsNoTrackingWithIdentityResolution() also skips the snapshot, but uses a temporary identity map during that query, so duplicates share one instance; the tracker is thrown away afterwards.I use tracking for entities I will modify, AsNoTracking for reads, and identity resolution when a no-tracking graph has shared references.
"A tracking query does two things for every entity it materialises. It puts it in the context's identity map, so if the same key comes back again, in this query or a later one, I get the same object instance. And it stores a snapshot of the original property values so
DetectChangescan compare them atSaveChanges. That's what lets me load an order, change a field and save without telling EF Core what changed. The price is memory, roughly an extra copy of each entity's values, and CPU for the identity lookup and snapshot.
AsNoTracking()turns both off. Entities come out as plain objects;SaveChangeswon't see them. It's the right default for read-only work, typically [20–40%] faster on large result sets and much lighter on memory. The catch is identity: if IIncludeorders with their customer and ten orders share one customer, I get ten separate customer objects. Usually harmless, but it can waste memory or break code that compares references.
AsNoTrackingWithIdentityResolution()sits in between. EF Core uses a standalone tracker for the duration of that query to dedupe instances, without snapshots, then discards it, so the result still isn't tracked. There's also a subtle tracking behaviour: if an entity is already tracked and modified in the context, a later tracking query returns the tracked instance with my unsaved values, not the database values. The mistake I see is the opposite one: no-tracking queries in a command handler, then callingUpdate()to save, which marks every column modified. So I track when I'm going to write and don't track when I'm only reading."
| Tracking (default) | AsNoTracking() |
AsNoTrackingWithIdentityResolution() |
|
|---|---|---|---|
| Identity map | Context-wide, persistent | None | Per query, discarded |
| Original-values snapshot | Yes | No | No |
| Same key twice | Same instance | Different instances | Same instance |
Seen by SaveChanges |
Yes | No | No |
| Relative cost | Highest | Lowest | Middle |
| Mode | Use when | Avoid when |
|---|---|---|
| Tracking | Loading entities to modify and save | Large read-only result sets |
AsNoTracking |
Read endpoints returning entities, exports | You'll modify and save the entities |
| Identity resolution | No-tracking graph with many shared references (e.g. same customer on many orders) | Flat results with no shared entities |
| DTO projection | Most reads | Never tracked anyway |
| API | Effect |
|---|---|
optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) |
All queries no-tracking unless .AsTracking() |
QueryTrackingBehavior.NoTrackingWithIdentityResolution |
Default to identity-resolving no-tracking |
db.ChangeTracker.QueryTrackingBehavior = ... |
Per context instance |
An export job read [200,000] orders with tracking on and peaked at [~1.6 GB]. Adding AsNoTracking() cut peak memory to [~700 MB] and runtime by [~35%]; projecting to a DTO took it to [~250 MB].
Checks that the candidate knows what the change tracker stores, what no-tracking gives up, and how identity resolution fits in.
Green flags
Red flags
Update() for every write.DbContext
└ StateManager
├ identity map: (EntityType, key) -> InternalEntityEntry
└ InternalEntityEntry
├ entity reference
├ EntityState (Unchanged, Modified, ...)
└ original values snapshot (array of property values)
For a tracking query, EF Core's shaper checks the identity map before materialising: if the key exists, it returns the existing instance and ignores the database row's values. Otherwise it creates the entity, snapshots it and registers it.
row -> materialise new instance -> fix-up navigations within this row's graph only -> return
No map lookup, no snapshot. Navigations between entities in the same result are still wired up (for example order.Customer), but each occurrence of a related row creates a new object.
query start: create a temporary StateManager-like map
row -> lookup key in temp map -> reuse or create
query end: map discarded, entities detached
No snapshots are taken, so it is cheaper than tracking, but there is still a dictionary lookup per entity.
var o1 = await db.Orders.SingleAsync(o => o.Id == 1); // tracked
o1.Status = OrderStatus.Cancelled; // not saved
var o2 = await db.Orders.SingleAsync(o => o.Id == 1); // same instance, Status = Cancelled
The second query hits the database but EF Core keeps the tracked instance's values. Use AsNoTracking() or Entry(o1).ReloadAsync() when you need fresh database values.
| Cost | Tracking | No-tracking |
|---|---|---|
| Allocation per entity | entity + entry + snapshot | entity |
DetectChanges at save |
scans all tracked entities | n/a |
| Long-lived context growth | unbounded unless cleared | none |
The tracker is also why a long-running context slows down: DetectChanges is O(tracked entities) and runs automatically on SaveChanges, and on some APIs such as Entries().
[MemoryDiagnoser].AsNoTracking() and check ReferenceEquals on two orders' customers; repeat with identity resolution.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) and use .AsTracking() in a command handler.db.ChangeTracker.Entries().Count() after each query in a loop.Choosing the tracking mode per use case.
namespace Shop.Orders;
using Microsoft.EntityFrameworkCore;
public sealed class OrderService(ShopDbContext db)
{
// Write: tracking so SaveChanges updates only the changed column.
public async Task CancelAsync(int id, CancellationToken ct)
{
var order = await db.Orders.SingleAsync(o => o.Id == id, ct);
order.Cancel(); // sets Status; snapshot comparison finds it
await db.SaveChangesAsync(ct); // UPDATE [Orders] SET [Status] = @p0 WHERE [Id] = @p1
}
// Read entities: no snapshot, no identity map.
public Task<List<Order>> RecentAsync(CancellationToken ct) =>
db.Orders.AsNoTracking()
.OrderByDescending(o => o.PlacedAt)
.Take(100)
.ToListAsync(ct);
// Read a graph with shared references: one Customer instance per key.
public Task<List<Order>> WithCustomersAsync(DateTimeOffset since, CancellationToken ct) =>
db.Orders.AsNoTrackingWithIdentityResolution()
.Where(o => o.PlacedAt >= since)
.Include(o => o.Customer)
.ToListAsync(ct);
}
// Program.cs: a read-heavy reporting service defaults to no-tracking.
builder.Services.AddDbContext<ReportingDbContext>(o => o
.UseSqlServer(builder.Configuration.GetConnectionString("Shop"))
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
// A rare write in that service opts back in explicitly:
var setting = await db.Settings.AsTracking().SingleAsync(s => s.Key == key, ct);
AsNoTracking() or a projection.AsNoTracking() and then calling Update() to save. Why it is wrong: Update marks every property modified, so EF Core writes all columns and can overwrite concurrent changes. Instead: load tracked for writes, or use ExecuteUpdate, with a RowVersion concurrency token.SaveChanges, and attaching it later throws "another instance with the same key is already being tracked". Instead: decide per use case: a command handler tracks what it changes, a query handler doesn't track at all.AsNoTracking() or ReloadAsync() for fresh values.DbContext across threads. Why it is wrong: the context and its connection are not thread-safe in any mode; parallel queries throw "A second operation was started on this context instance". Instead: one context per unit of work, or IDbContextFactory for parallel work.AsNoTracking() to DTO projections. Why it is wrong: DTOs are never tracked, so it does nothing. Instead: only add it where entities are returned.DetectChanges slows down. Instead: short-lived contexts, ChangeTracker.Clear() between batches.Tracking is a write-side feature. I set the default per context by its job: a reporting context defaults to NoTracking; a command-side context keeps tracking. Identity resolution is a niche tool for no-tracking graphs with heavy sharing; projections usually make it unnecessary.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Tracking | Command handlers that modify entities | Snapshot + identity map per entity | Read-only, large results |
AsNoTracking |
Read entities, exports | Duplicate instances for shared rows | When saving changes later |
| Identity resolution | No-tracking graphs with shared references | Dictionary lookup per entity | Flat results |
| Projection | Most reads | DTO per use case | Writes |
I choose by state and thread safety, then check dependencies:
So: DbContext is scoped (not thread-safe, one unit of work), or created per operation with IDbContextFactory<T> outside requests. HttpClient comes from IHttpClientFactory (pooled handlers, DNS refresh) or is one singleton with PooledConnectionLifetime. IMemoryCache is a singleton. The trade-off is sharing versus safety: wider lifetimes save allocations but demand thread safety and stricter dependencies.
Update() attaches the entity graph and marks every property Modified, because EF Core has no snapshot of original values to compare against, so it can't tell which properties actually changed. It sends all columns, which silently overwrites (loses) other users' concurrent edits and wastes I/O. Instead: load the entity tracked and apply the DTO's changes (only changed columns are written); or attach and set Entry(e).Property(x => x.Name).IsModified = true for specific fields; or use ExecuteUpdate for set-based changes in one statement without loading. Always add a RowVersion concurrency token ([Timestamp] byte[]): EF Core adds it to the WHERE clause and throws DbUpdateConcurrencyException if someone else changed the row, which you turn into a 409.
A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.
Last updated 23 Nov 2026.