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.
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.
"That message is EF Core enforcing its identity map: within one
DbContextthere can only be one tracked object forOrder42. 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 newOrder { Id = 42 }and callsdb.Update(order).Updatewalks 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'sMap<Order>(dto)creating new child objects for lines that already exist, and aDbContextregistered 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,UpdateorAdd, then printChangeTracker.DebugView.LongViewjust 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 withEntry(existing).State = DetachedorAsNoTracking()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."
| 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 |
| 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 |
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].
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
Update pattern as the usual cause.ChangeTracker.DebugView and the stack trace to diagnose.DbContext lifetime as a possible cause.Red flags
AsNoTracking() until it goes away.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.
| 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 |
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.
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.
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.
Attach a new instance with the same key and read the exception message.AnyAsync for the existence check and confirm no error.Product key twice and call Update; then use foreign keys only.options.EnableSensitiveDataLogging() in a test and compare the message (it shows key values only then in some versions).DbContext as singleton in a sample app and send two requests to reproduce cross-request tracking.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);
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.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.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.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.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.ChangeTracker.Clear() or a new context per attempt.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.