EF Core: The instance of entity type cannot be tracked
Two C# objects with the same key cannot share a DbContext. Load the tracked row, copy values onto it, and keep read paths no-tracking.

Introduction & Quick Summary
An update endpoint starts failing after a refactor:
System.InvalidOperationException: The instance of entity type 'Customer' cannot be
tracked because another instance with the same key value for {'Id'} is already
being tracked. When attaching existing entities, ensure that only one entity
instance with a given key value is attached.Quick answer: two different C# objects represent the same database row, and both are in the same DbContext. EF Core keeps one tracked instance per key, so it refuses the second. Stop attaching a second copy: either load the tracked instance and copy values into it, or keep the context read-only.
var existing = await db.Customers.FindAsync(dto.Id); // tracked instance, or null
if (existing is null) return NotFound();
db.Entry(existing).CurrentValues.SetValues(dto); // copy values onto the tracked copy
await db.SaveChangesAsync();The exception is a guard, not a bug. A context's change tracker is an identity map: for a given entity type and key it holds exactly one instance, so that SaveChanges knows what changed and so navigation fixes stay consistent. Update, Attach and a second query that reads the same row all try to add another instance, and the tracker rejects the duplicate.
The message names the key property ({'Id'}) and the type. That is enough to find both instances: one came from a query and is already tracked, the other came from Update, Attach, JSON deserialization or a manual projection.
Core Mechanics, Signatures & Reproducible Setup
Reproduce with SQLite, which needs no server:
dotnet new console -n tracker && cd tracker
dotnet add package Microsoft.EntityFrameworkCore.Sqliteusing Microsoft.EntityFrameworkCore;
var db = new ShopContext();
await db.Database.EnsureCreatedAsync();
var a = await db.Customers.FirstAsync(); // tracked
var b = new Customer { Id = a.Id, Name = "other" }; // second instance, same key
db.Update(b); // throws InvalidOperationException| Operation | Adds to tracker | Throws on duplicate key | Typical caller |
|---|---|---|---|
| Query with tracking (default) | yes | no, returns the tracked instance | read paths |
Query with AsNoTracking() | no | no | read-only projections |
Find / FindAsync | yes, or returns the tracked one | no | load by key |
Attach(entity) | yes, state Unchanged | yes | detached graphs |
Update(entity) | yes, state Modified | yes | detached graphs |
Entry(e).State = ... | yes | yes | fine-grained control |
ChangeTracker.Clear() | removes all | n/a | unit-of-work reset |
Key Comparison Table
| Goal | Correct call | Why it avoids the error |
|---|---|---|
| Update one entity by id | FindAsync(id) then SetValues(dto) | reuses the tracked instance |
| Update a detached graph | Update(root) with a single instance per key | tracker sees each key once |
| Read for display | AsNoTracking() | nothing is tracked |
| Read a graph for display | AsNoTrackingWithIdentityResolution() | deduplicates without tracking |
| Insert a new row | Add(entity) with a zero/default key | no existing key to collide |
| Delete by id | new Customer { Id = id } then Remove | stub has no other tracked copy |
What each exception variant usually means:
| Message detail | Usual cause | Fix |
|---|---|---|
same key value for {'Id'} | two instances of one row | use Find and copy values |
same key value for {'TenantId', 'Slug'} | composite key duplicated in a graph | deduplicate before Update |
after Attach of a graph | child entities repeated across parents | split the graph or use AsNoTracking reads |
| only in tests | shared context between tests | new context per test |
| only under load | singleton or long-lived context | scope per request |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Copy values instead of attaching a second copy
public async Task<bool> UpdateAsync(CustomerDto dto, CancellationToken ct)
{
var entity = await db.Customers.FindAsync([dto.Id], ct);
if (entity is null) return false;
db.Entry(entity).CurrentValues.SetValues(dto);
await db.SaveChangesAsync(ct);
return true;
}SetValues copies scalar properties from a DTO or another instance onto the tracked entity and marks exactly the changed ones. It does not touch navigations, so a request that changes an address needs those mapped explicitly — which is usually what an API boundary should require anyway.
2. Update on a graph with repeated keys
var order = JsonSerializer.Deserialize<Order>(json)!; // Address objects with Id 7 appear twice
db.Update(order); // throws when the second Address is attachedA JSON graph can carry the same related row twice: two orders sharing one address, a cart line and a shipment pointing at the same product. Fix the graph before it reaches the tracker:
var seen = new Dictionary<(Type, object), object>();
foreach (var entry in db.ChangeTracker.Entries()) { /* inspect */ }
// or deduplicate by id in the DTO layer
order.Lines = order.Lines
.GroupBy(l => l.ProductId)
.Select(g => g.First())
.ToList();For genuinely detached graphs, load the root with tracking and map the rest, rather than Update on the whole object tree.
3. Read-only queries that later write
var list = await db.Products.AsNoTracking().ToListAsync(); // no tracking
list[0].Price = 10m;
await db.SaveChangesAsync(); // saves nothingMixing modes in one request is the source of both this error and its opposite (silent no-op saves). Choose per operation: AsNoTracking for endpoints that only render data, tracking for endpoints that write. AsNoTrackingWithIdentityResolution returns a graph whose repeated entities are the same object, which prevents duplicate-key errors if the result is later handed to Update.
4. Identity from a Find versus a fresh instance
var tracked = await db.Customers.FindAsync(id); // may already be in the tracker
var copy = new Customer { Id = id, Name = "new" };
db.Update(copy); // throws if tracked is not nullFind is cheap: if the entity is already tracked it returns that instance without a query. That also means a Find can return stale values from an earlier query in the same context — one reason a request-scoped context is the right size. When only a stub is needed, construct the key-only object and set the state:
var stub = new Customer { Id = id };
db.Attach(stub);
stub.Name = "new";
await db.SaveChangesAsync();5. Context lifetime: the real fix for most incidents
A DbContext registered as a singleton, kept in a background service, or stored in a static field accumulates tracked entities until it hits this error and, later, a memory problem:
builder.Services.AddDbContext<ShopContext>(o => o.UseSqlite(conn)); // scoped by default
builder.Services.AddDbContextFactory<ShopContext>(o => o.UseSqlite(conn)); // for background workBackground jobs and Blazor components should create a context per unit of work with IDbContextFactory<T> and dispose it. When a long unit of work genuinely needs several steps, db.ChangeTracker.Clear() between steps resets the identity map, at the cost of re-querying anything needed later. The connection string and provider settings belong in configuration; compare environments with the env formatter when one environment fails and another does not.
6. Composite keys, owned types and tests
modelBuilder.Entity<OrderLine>().HasKey(l => new { l.OrderId, l.ProductId });Composite keys produce the same message with both properties quoted. Owned types have no key of their own and are tracked through their owner, so duplicating an owner duplicates its owned instance too. In tests, a shared context between test methods leaves tracked entities behind and the second test fails on a key the first test already loaded — create the context inside each test or call ChangeTracker.Clear() in setup. A JSON payload that triggers the error is easier to read through the JSON formatter than in a debugger watch window.
Common Compilation/Runtime Mistakes & Version Gotchas
Calling Update for every write. Update attaches the whole graph as Modified, issuing updates for every column and colliding with tracked rows. Use Find plus SetValues for single-row updates.
Using AsNoTracking and expecting updates. Nothing is tracked, so SaveChanges returns 0. The inverse mistake, mixing a detached read with a tracked one, produces the duplicate-key error instead.
Assuming Attach marks nothing. Attach marks the root Unchanged and discovers navigation properties; children in a Modified state come from Update. Both add instances to the tracker.
Sharing one context across parallel tasks. DbContext is not thread-safe, and concurrent use throws either this error or A second operation was started on this context. One context per unit of work, never per Task.WhenAll branch.
Ignoring the offending key in the message. The quoted properties identify which duplicate to look for; a generic "detach everything" fix hides a graph that will collide again.
Version notes. EF Core 5 changed Update to mark keyless or generated-key children as Added rather than Modified, which alters which duplicates throw. EF Core 7 added ExecuteUpdate and ExecuteDelete, bulk operations that bypass the tracker entirely — useful when the goal is to change rows without loading them. EF Core 9 keeps the identity-map rule unchanged.
Reference material: Change tracking in EF Core and Tracking vs no-tracking queries.
Official references
primary documentationThe C# documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC#: NullReferenceException: Object reference not set
The message never names the null. Read the stack trace, enable nullable reference types, and use null-conditional access instead of guessing.
C# CS7036: no argument given that corresponds to the required parameter
CS7036 means the chosen constructor or method expects an argument the caller skipped. Match the signature instead of casting or adding a null default.
C# CS0117: 'X' does not contain a definition for 'Y'
CS0117 means the compiled assembly has no such member, usually from an older target framework or package. Check the API surface before editing code.
C# CS0246: The type or namespace name could not be found
CS0246 is a compile-time resolution failure: a missing using, package, target framework, or an unrestored project. Trace it backward from the symbol.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.