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

**Code:** `cannot be tracked because another instance with the same key` · **Category:** .NET · **Seen on:** .NET

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

## 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

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/dotnet/entity-already-being-tracked)
