cannot be tracked because another instance with the same key 🟪 .NET

The instance of entity type 'X' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked

Two different objects with the same primary key were attached to one DbContext.

Seen on: .NET

Meaning

Typical in update endpoints: the entity was loaded (tracked) earlier in the request, then a new instance from the request body with the same Id is attached via Update(). Use the tracked instance, or load with AsNoTracking.

Common causes

  • Calling Update() with a DTO-mapped entity after loading the same Id
  • Long-lived context accumulating tracked entities
  • Graph containing the same entity twice

⚡ Quick fix

  1. Load the entity and copy values onto it (SetValues)
  2. Use AsNoTracking for read queries
  3. Keep DbContext per request

Detailed fix by platform

C#

  1. csharp
    var existing = await db.Products.FindAsync(dto.Id);
    db.Entry(existing!).CurrentValues.SetValues(dto);
    await db.SaveChangesAsync();

How to diagnose

  1. Tracking — Was the entity loaded earlier?
  2. Lifetime — Context scope

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.