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

📚 Interview question

Your API's update endpoint throws InvalidOperationException: "The instance of entity type 'Order' cannot be tracked because another instance with the key value '{Id: 42}' is already being tracked." How do you diagnose the cause and fix it properly?

Covers the EF Core identity-conflict error: the identity map rule of one instance per key per context, the common causes (Attach/Update after a tracking load, duplicate objects in a graph, long-lived or singleton contexts, AutoMapper creating new instances), how to diagnose with ChangeTracker.DebugView, and the correct fixes.

Mid-Level Debugging Intermediate aspnet-core change-tracking dbcontext debugging ef-core identity-resolution

🎯 Key points

  • The identity map allows one tracked instance per entity type and key per DbContext
  • Thrown by Attach, Update, Add or graph traversal when a second instance with a tracked key arrives
  • Typical cause: tracking load (or validation query) then Update() of a DTO-built entity with the same id
  • Other causes: the same key twice in one graph, a DbContext registered as singleton or reused across requests, a mapper creating new child instances
  • Diagnose with ChangeTracker.DebugView.LongView and the stack trace of who tracked the first instance
  • Fix: apply changes to the already-tracked instance (or CurrentValues.SetValues), not a second copy
  • Use AsNoTracking for validation reads; check DbSet.Local before attaching
  • Never fix it by detaching randomly or making the context long-lived; keep one context per request

⏱ 30-second answer

The identity map allows one tracked instance per key per DbContext. The error means a second object with key 42 reached Attach, Update, Add or a graph traversal while another instance was already tracked.

The usual cause: the handler loads the order with a tracking query (often for validation), then builds a new Order from the DTO and calls Update() on it. Other causes are the same child twice in a posted graph, a mapper creating new instances for existing children, or a DbContext that lives too long (singleton or reused across requests).

I diagnose with ChangeTracker.DebugView.LongView and the stack trace, then fix the flow: apply the changes to the instance already tracked, use AsNoTracking() for read-only checks, and keep one context per request. Detaching entities to silence it hides the design bug.

🗣 Full answer (senior)

How I would answer this in an interview

"That message is EF Core enforcing its identity map: within one DbContext there can only be one tracked object for Order 42. So the question is always: who tracked the first instance, and where did the second one come from? In an API it's almost always the same pattern. The handler loads the order to validate it, maybe checks it exists or checks the status, with a normal tracking query. Then it maps the request DTO onto a new Order { Id = 42 } and calls db.Update(order). Update walks the graph, finds key 42 already tracked, and throws.

For example, at [company] we had [an order amendment endpoint] that started failing after someone added an 'exists' check using FindAsync. The fix wasn't to detach anything; it was to apply the DTO to the entity we'd just loaded, which also meant the UPDATE only touched the changed columns. [It removed N errors a day and halved the SQL for that endpoint.] Other causes I look for: a posted graph containing the same product twice in different lines, AutoMapper's Map<Order>(dto) creating new child objects for lines that already exist, and a DbContext registered as a singleton or captured by a singleton, so entities from earlier requests are still tracked. That last one also shows up as data from other requests and memory growth.

To diagnose, I read the stack trace to see which call threw, Attach, Update or Add, then print ChangeTracker.DebugView.LongView just before it to see what's tracked and in which state. If the tracked entity surprises me, I look at the DI registration and lifetime. The mistake I see is fixing it with Entry(existing).State = Detached or AsNoTracking() sprinkled around until the error disappears. That usually trades an exception for a silent lost update. The real fix is one instance per key: load it, change it, save it."


Causes and fixes

Cause How it looks Fix
Tracking load, then Update(newInstance) Load for validation, map DTO to new entity Apply changes to the loaded instance
FindAsync / Any check that tracks FindAsync tracks the result Use the found instance, or AnyAsync (does not track)
Same key twice in a posted graph Two lines reference new Product { Id = 5 } Attach one instance per key, or set only the FK (ProductId = 5)
Mapper creates new children mapper.Map(dto, order) replaces Lines with new objects Reconcile collections by key
Long-lived context Singleton DbContext, or a context captured by a singleton Scoped context, IDbContextFactory in singletons
Retried operation in same context First attempt left entities tracked ChangeTracker.Clear() or a fresh context per attempt

Diagnosis steps

Step Tool
Which call threw Stack trace: StateManager.StartTracking under Attach/Update/Add
What is tracked db.ChangeTracker.DebugView.LongView before the call
Is the instance local db.Orders.Local.FirstOrDefault(o => o.Id == 42)
Is the context too long-lived DI registration, ValidateScopes, active-db-contexts in dotnet-counters

Production example

An endpoint threw this error on [~3%] of order amendments: only those whose payload included a line for a product already loaded earlier in the request. Reconciling lines by key instead of letting the mapper create new instances removed the errors and cut the endpoint's SQL from [~14] statements to [~4].

🔍 What the interviewer is checking

Checks that the candidate understands the identity map, can find where the second instance comes from, and fixes the flow rather than suppressing the error.

Green flags

  • Explains one tracked instance per key per context.
  • Names the load-then-Update pattern as the usual cause.
  • Uses ChangeTracker.DebugView and the stack trace to diagnose.
  • Checks the DbContext lifetime as a possible cause.

Red flags

  • Fixes it by detaching entities or adding AsNoTracking() until it goes away.
  • Suggests a singleton or long-lived context.
  • Cannot explain why EF Core enforces the rule.

📚 Learn in depth

1. The identity map

StateManager
  identity map: (Order, 42) -> InternalEntityEntry -> instance A

Attach(instance B with Id 42)
  -> lookup (Order, 42) -> found A, and A is not B
  -> throw InvalidOperationException (identity conflict)

The rule exists because EF Core needs one authoritative set of original and current values per row. Two instances with different values for the same row would make the UPDATE ambiguous.

2. Which APIs track

API Tracks?
db.Orders.Where(...).ToListAsync() Yes (default)
FindAsync(id) Yes; returns the tracked instance without a query if already tracked
AnyAsync, CountAsync, projections to DTOs No entity tracked
AsNoTracking() queries No
Attach, Update, Add, Remove Yes, for the whole reachable graph

3. Graph traversal surprises

var order = new Order { Id = 42, Lines =
[
    new OrderLine { Id = 1, Product = new Product { Id = 5 } },
    new OrderLine { Id = 2, Product = new Product { Id = 5 } },   // second instance, same key
]};
db.Update(order);   // throws on the second Product

Setting the foreign key (ProductId = 5) instead of the navigation avoids tracking a product at all.

4. Lifetime causes

Singleton service --captures--> DbContext (meant to be scoped)
request 1: loads Order 42  -> tracked forever
request 2: Update(Order 42 from DTO) -> identity conflict

ValidateScopes (on by default in Development) catches a scoped DbContext injected into a singleton at resolution time. A context registered directly as singleton is not caught: look at AddDbContext lifetime arguments.

5. Why detaching is a smell

Entry(existing).State = EntityState.Detached followed by Update(copy) works, but it throws away the snapshot, writes every column and skips any concurrency token original value, so it can overwrite concurrent changes.

Try it yourself

  1. Load an entity tracked, then Attach a new instance with the same key and read the exception message.
  2. Repeat with AnyAsync for the existence check and confirm no error.
  3. Build a graph with the same Product key twice and call Update; then use foreign keys only.
  4. Enable options.EnableSensitiveDataLogging() in a test and compare the message (it shows key values only then in some versions).
  5. Register a DbContext as singleton in a sample app and send two requests to reproduce cross-request tracking.

💻 Code

Before and after: the endpoint that triggered the error.

// BEFORE: tracking load for validation, then Update() of a second instance.
public async Task<IResult> AmendAsync(int id, AmendOrderRequest req, ShopDbContext db, CancellationToken ct)
{
    // Instance A: FindAsync TRACKS the result. The identity map now holds (Order, 42) -> A.
    var existing = await db.Orders.FindAsync([id], ct);
    if (existing is null) return Results.NotFound();
    if (existing.Status != OrderStatus.Open) return Results.Conflict();

    // Instance B: a different object with the same key, built from the request.
    var order = new Order { Id = id, Notes = req.Notes, DeliverOn = req.DeliverOn };

    // Diagnosis: this prints "Order {Id: 42} Unchanged" - A is already tracked.
    Console.WriteLine(db.ChangeTracker.DebugView.ShortView);

    // Update walks B, finds (Order, 42) already mapped to A (not B) and throws:
    // "The instance of entity type 'Order' cannot be tracked because another instance
    //  with the key value '{Id: 42}' is already being tracked."
    db.Orders.Update(order);
    await db.SaveChangesAsync(ct);
    return Results.NoContent();
}
namespace Shop.Orders;

using Microsoft.EntityFrameworkCore;

public sealed record AmendOrderRequest(string? Notes, DateOnly DeliverOn, byte[] RowVersion);

public static class AmendOrderEndpoint
{
    // AFTER: one instance per key. Load it, check it, change it, save it.
    public static async Task<IResult> AmendAsync(int id, AmendOrderRequest req, ShopDbContext db, CancellationToken ct)
    {
        var order = await db.Orders.SingleOrDefaultAsync(o => o.Id == id, ct);
        if (order is null) return Results.NotFound();
        if (order.Status != OrderStatus.Open) return Results.Conflict();

        db.Entry(order).Property(o => o.RowVersion).OriginalValue = req.RowVersion;
        order.Notes = req.Notes;         // DetectChanges writes only changed columns
        order.DeliverOn = req.DeliverOn;

        try
        {
            await db.SaveChangesAsync(ct);
        }
        catch (DbUpdateConcurrencyException)
        {
            return Results.Conflict();   // someone else changed the order since the client read it
        }
        return Results.NoContent();
    }
}
// Diagnosis helper while reproducing locally.
logger.LogDebug("Tracked before attach:{NewLine}{View}", Environment.NewLine, db.ChangeTracker.DebugView.LongView);

⚠ Common mistakes

  • Mistake: Loading an entity to validate it, then calling Update() on a new instance built from the DTO. Why it is wrong: two instances with the same key in one context break the identity map. Instead: apply the DTO to the loaded instance.
  • Mistake: Silencing the error by setting the existing entry to Detached. Why it is wrong: the second instance is then saved with every column modified and no original values, overwriting concurrent changes. Instead: work with the tracked instance.
  • Mistake: Using FindAsync just to check existence. Why it is wrong: it tracks the entity, setting up the conflict. Instead: AnyAsync, or keep and use the found instance.
  • Mistake: Setting navigation objects such as line.Product = new Product { Id = 5 } on graphs you attach. Why it is wrong: each new is another instance of the same key. Instead: set the foreign key property ProductId.
  • Mistake: Registering DbContext as a singleton, or injecting it into a singleton service. Why it is wrong: entities from earlier requests stay tracked, causing conflicts, stale data and memory growth. Instead: scoped contexts, and IDbContextFactory<T> inside singletons and background services.
  • Mistake: Letting AutoMapper map a DTO graph onto an existing entity's collections. Why it is wrong: it often replaces collection items with new instances that share keys with tracked ones. Instead: reconcile children by key in code.
  • Mistake: Retrying a failed save in the same context after re-loading data. Why it is wrong: the first attempt's entities are still tracked. Instead: ChangeTracker.Clear() or a new context per attempt.

🏛 Senior insight: trade-offs

This error is a gift: EF Core is refusing to guess which of two objects represents row 42. I treat it as a sign that the handler's flow is muddled, not as something to suppress. The clean shape is "one instance per key per unit of work": a command handler loads what it changes, mutates it, and saves; reads that don't change anything use no-tracking or projections so they can't collide.

Fix When it fits Cost When not to
Apply changes to the tracked instance Almost always None —
AsNoTracking() for validation reads Read-only checks before a write via ExecuteUpdate Extra query if you later need to track When you will modify the same entity
Check DbSet.Local before attaching Graph attach code A local lookup As a blanket fix for unclear flows
ChangeTracker.Clear() Retries, batch loops Loses all tracked state Mid-way through a unit of work
Detach then Update Almost never Lost updates, every column written Anything with concurrent users

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Update() or Attach on DTO-built entities. Why: Checks the wider disconnected-entity patterns and why Update writes every column.
    How to answer

    All three walk the whole graph and set states based on whether each entity has a key value:

    • Add: everything becomes Added, so EF Core inserts it.
    • Attach: entities with a key become Unchanged, without one become Added. Nothing is written until you change something.
    • Update: entities with a key become Modified with every property marked, because EF Core has no original values to compare with, so it writes every column.

    That makes Update dangerous for APIs: it overwrites columns the client never meant to change and silently loses concurrent edits. Better: accept a use-case DTO containing only the editable fields (so nothing can be over-posted), load the entity tracked and apply the DTO so only real changes are written, use Attach plus IsModified for a known partial update, or ExecuteUpdate for set-based changes, always with a RowVersion set as the original value. The trade-off is one extra read in exchange for correct, minimal updates.

  2. When: Candidate suggests AsNoTracking for the validation read. Why: Checks the tracking vs no-tracking trade-offs and identity resolution.
    How to 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.

  3. When: Candidate suspects a long-lived or singleton DbContext. Why: Checks DbContext lifetime choices in DI.
    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.

🛠 Real-world problems: how you handle them

Identity conflict on order amendments after adding an existence check
Situation
An [order management] API on ASP.NET Core and Azure SQL, [~200] amendments an hour from a mobile app; a recent change added a 'does the order exist and is it open' check at the top of the handler.
Signals
Application Insights showed a spike of `InvalidOperationException` (identity conflict) on `PUT /orders/{id}` after the release, [~3%] of requests, all returning 500; users reported 'Something went wrong' when changing delivery dates.
Investigation
The stack trace pointed at `DbSet.Update` inside the handler. Reproduced locally with the failing payload and printed `ChangeTracker.DebugView.LongView` before `Update`: `Order {Id: 42} Unchanged` was already tracked from the new `FindAsync` check. Lines with repeated products also produced the error from the mapper creating `Product` instances.
Resolution
Hotfix: replaced `FindAsync` with `AnyAsync` for the existence check to stop the 500s. Proper fix: rewrote the handler to load the order with its lines once, check status and row version, apply the DTO fields, reconcile lines by key with `ProductId` foreign keys instead of navigations, and save.
Prevention
Integration tests for amendments with repeated products; a code-review rule against `Update(` in command handlers; an Application Insights alert on `InvalidOperationException` rate per endpoint; handler template that loads, mutates and saves.

How to tell it (STAR)

**S:** At [company], right after a release our order amendment endpoint started returning 500s for [about 3%] of requests. **T:** I was on call and needed to stop the errors and find the real cause. **A:** The stack trace showed EF Core's identity conflict inside `Update`. I reproduced it and dumped `ChangeTracker.DebugView`, which showed the order was already tracked by a new `FindAsync` existence check. I shipped a quick fix using `AnyAsync`, then rewrote the handler to load the order once, apply the DTO to that instance and reconcile lines by key. **R:** The errors went to [zero], the endpoint's SQL dropped from [~14] statements to [~4], and we added a review rule against `Update()` in handlers.

More in Change Tracking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me