Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readC#
#csharp#ef-core#entity-framework#dbcontext
Bold white headline reading ALREADY TRACKED with an EF Core entity crate holding two amber key plates at one cyan identity slot.

Introduction & Quick Summary

An update endpoint starts failing after a refactor:

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

csharp
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:

bash
dotnet new console -n tracker && cd tracker dotnet add package Microsoft.EntityFrameworkCore.Sqlite
csharp
using 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
OperationAdds to trackerThrows on duplicate keyTypical caller
Query with tracking (default)yesno, returns the tracked instanceread paths
Query with AsNoTracking()nonoread-only projections
Find / FindAsyncyes, or returns the tracked onenoload by key
Attach(entity)yes, state Unchangedyesdetached graphs
Update(entity)yes, state Modifiedyesdetached graphs
Entry(e).State = ...yesyesfine-grained control
ChangeTracker.Clear()removes alln/aunit-of-work reset

Key Comparison Table

GoalCorrect callWhy it avoids the error
Update one entity by idFindAsync(id) then SetValues(dto)reuses the tracked instance
Update a detached graphUpdate(root) with a single instance per keytracker sees each key once
Read for displayAsNoTracking()nothing is tracked
Read a graph for displayAsNoTrackingWithIdentityResolution()deduplicates without tracking
Insert a new rowAdd(entity) with a zero/default keyno existing key to collide
Delete by idnew Customer { Id = id } then Removestub has no other tracked copy

What each exception variant usually means:

Message detailUsual causeFix
same key value for {'Id'}two instances of one rowuse Find and copy values
same key value for {'TenantId', 'Slug'}composite key duplicated in a graphdeduplicate before Update
after Attach of a graphchild entities repeated across parentssplit the graph or use AsNoTracking reads
only in testsshared context between testsnew context per test
only under loadsingleton or long-lived contextscope per request

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Copy values instead of attaching a second copy

csharp
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

csharp
var order = JsonSerializer.Deserialize<Order>(json)!; // Address objects with Id 7 appear twice db.Update(order); // throws when the second Address is attached

A 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:

csharp
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

csharp
var list = await db.Products.AsNoTracking().ToListAsync(); // no tracking list[0].Price = 10m; await db.SaveChangesAsync(); // saves nothing

Mixing 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

csharp
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 null

Find 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:

csharp
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:

csharp
builder.Services.AddDbContext<ShopContext>(o => o.UseSqlite(conn)); // scoped by default builder.Services.AddDbContextFactory<ShopContext>(o => o.UseSqlite(conn)); // for background work

Background 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

csharp
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 documentation

The C# documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.