📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between a tracking query, AsNoTracking() and AsNoTrackingWithIdentityResolution() in EF Core? What does each cost, how does each handle the same row appearing twice, and which would you use where?

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.

Intermediate Theory Intermediate asnotracking change-tracking ef-core identity-resolution performance querying

🎯 Key points

  • Tracking: entities added to the change tracker with an original-values snapshot; SaveChanges detects changes
  • Tracking gives identity resolution: one instance per key per context
  • AsNoTracking: no snapshot, no identity map; same row twice = two instances
  • AsNoTrackingWithIdentityResolution: dedupes instances during the query, then discards the tracker
  • Tracked entities already in the context win over database values in later tracking queries
  • The SQL is identical in all modes: the saving is CPU and memory in the app, which shows under load as GC and p95 latency
  • QueryTrackingBehavior.NoTracking as a context default for read-heavy services
  • Tracking mode does not make a DbContext thread-safe; optimistic concurrency still needs a concurrency token

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 DetectChanges can compare them at SaveChanges. 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; SaveChanges won'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 I Include orders 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 calling Update() 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."


The three modes

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

When to use each

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

Setting a default

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

Production example

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].

🔍 What the interviewer is checking

Checks that the candidate knows what the change tracker stores, what no-tracking gives up, and how identity resolution fits in.

Green flags

  • Mentions the snapshot and identity map.
  • Explains duplicate instances with no-tracking.
  • Knows identity resolution is per query and still not tracked.
  • Ties tracking to writes and no-tracking to reads.

Red flags

  • "AsNoTracking makes the SQL faster."
  • Uses no-tracking plus Update() for every write.
  • Unaware that tracked instances shadow database values.

📚 Learn in depth

1. What the change tracker stores

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.

2. No-tracking path

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.

3. Identity resolution without tracking

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.

4. The 'stale' tracked instance

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.

5. Costs

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().

Try it yourself

  1. Load 10,000 rows tracked and untracked; compare with BenchmarkDotNet [MemoryDiagnoser].
  2. Include orders with their customer using AsNoTracking() and check ReferenceEquals on two orders' customers; repeat with identity resolution.
  3. Modify a tracked entity without saving, query it again with tracking, and inspect the value.
  4. Set UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) and use .AsTracking() in a command handler.
  5. Print db.ChangeTracker.Entries().Count() after each query in a loop.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Using tracking queries for large read-only lists. Why it is wrong: every entity gets a snapshot and identity-map entry, roughly doubling memory. Instead: AsNoTracking() or a projection.
  • Mistake: Loading with 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.
  • Mistake: Mixing tracking and no-tracking queries for the same entity in one context. Why it is wrong: you end up with a tracked instance and a detached copy of the same row; editing the copy is silently ignored by 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.
  • Mistake: Assuming a tracking query always returns database values. Why it is wrong: an already-tracked instance is returned with its in-memory values. Instead: use AsNoTracking() or ReloadAsync() for fresh values.
  • Mistake: Thinking no-tracking queries make it safe to share a 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.
  • Mistake: Comparing no-tracking entities by reference. Why it is wrong: the same row can be two instances. Instead: compare keys, or use identity resolution.
  • Mistake: Adding AsNoTracking() to DTO projections. Why it is wrong: DTOs are never tracked, so it does nothing. Instead: only add it where entities are returned.
  • Mistake: Keeping one context alive and tracking thousands of entities. Why it is wrong: memory grows and DetectChanges slows down. Instead: short-lived contexts, ChangeTracker.Clear() between batches.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the DbContext lifetime or a long-lived context. Why: Checks DbContext lifetime choices that affect tracking growth.
    How to answer

    I choose by state and thread safety, then check dependencies:

    1. Does it hold per-unit-of-work state (a change tracker, the current user)? → scoped.
    2. Is it shared, thread-safe and worth building once (a cache, a client pool, compiled config)? → singleton.
    3. Stateless and cheap? → transient (or singleton if every dependency is a singleton).
    4. A service can't outlive its shortest-lived dependency.

    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.

  2. When: Candidate mentions loading with AsNoTracking and saving later. Why: Checks understanding of disconnected updates and their risks.
    How to answer

    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.

  3. When: Candidate suggests sharing one context for parallel read queries. Why: Checks that the candidate knows DbContext is not thread-safe in any tracking mode.
    How to answer

    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.

↩ Usually asked after

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me