LESSON 3 OF 19

The Same Entity Is Tracked Twice: Solving Detached Updates and Tracking Conflicts

Learn how to diagnose duplicate tracking conflicts in EF Core and build safe update flows with AsNoTracking, Attach, Entry.State and existing-entity updates.

35 dk 100

Introduction

In web applications, an entity is often updated after it has traveled through an HTTP request, message queue or another service. It is therefore no longer connected to the DbContext that originally loaded it. This is called a detached entity. Detached entities are normal, but a conflict occurs when a detached instance is attached to a context that is already tracking a different instance with the same key.

In this lesson, using EF Core 10 and .NET 10, we will reproduce the problem, inspect the ChangeTracker and compare three update strategies: loading the existing entity and changing its properties, updating a detached entity directly and using Attach or Entry.State with clearly defined boundaries.

The central rule is simple: one DbContext should track only one entity instance for a given entity type and primary key. EF Core enforces this identity-resolution rule because two objects representing the same database row may contain different property values or relationships.

Model and DbContext

The following model represents a product whose name, price and inventory quantity can be updated. In production systems, using a DTO instead of exposing an entity directly is usually safer. The simple model below makes tracking behavior easy to see.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public int StockQuantity { get; set; }
    public byte[] RowVersion { get; set; } = [];
}

public class AppDbContext : DbContext
{
    public DbSet<Product> Products => Set<Product>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>()
            .Property(p => p.RowVersion)
            .IsRowVersion();
    }
}

The RowVersion property is included for optimistic concurrency. Although this lesson focuses on tracking, detached updates must also consider how to avoid overwriting changes made by another user.

Reproducing the exception

First, query the product in the same context. Because queries are tracking by default, productFromDatabase is placed in the ChangeTracker.

await using var context = new AppDbContext(options);

var productFromDatabase = await context.Products
    .SingleAsync(p => p.Id == 7);

var incomingProduct = new Product
{
    Id = 7,
    Name = "New product name",
    Price = 149.90m,
    StockQuantity = 25
};

context.Update(incomingProduct);
await context.SaveChangesAsync();

Two different objects now have the same key: productFromDatabase, loaded from the database, and incomingProduct, received from the client. When Update tries to track the second object, EF Core typically throws an InvalidOperationException similar to: “The instance of entity type 'Product' cannot be tracked because another instance with the key value '{Id: 7}' is already being tracked.”

The problem is not that the database contains two rows with the same Id. The problem is that one DbContext contains two CLR objects representing the same row. You can inspect this state through context.ChangeTracker.Entries<Product>().

foreach (var entry in context.ChangeTracker.Entries<Product>())
{
    Console.WriteLine($"Id={entry.Entity.Id}, State={entry.State}");
}

Approach 1: Reading with AsNoTracking

Use AsNoTracking when an entity is only being displayed, projected or sent to another layer. The query does not add the returned entity to the ChangeTracker.

var product = await context.Products
    .AsNoTracking()
    .SingleAsync(p => p.Id == 7);

This is useful for read-only operations because it avoids tracking overhead. However, AsNoTracking is not by itself an update strategy. The following code can work because only one Product instance is later attached to the context:

var product = await context.Products
    .AsNoTracking()
    .SingleAsync(p => p.Id == 7);

product.Price = 159.90m;
context.Products.Update(product);
await context.SaveChangesAsync();

The risk is that Update can mark all updatable properties as modified. If a DTO omits a property or contains its default value, that value may be written to the database unintentionally. Be especially careful when implementing partial updates.

Approach 2: Load the existing entity and apply changes

For most business applications, the clearest and safest approach is to query the current entity with the context used for the update and then change only the properties that the operation allows.

public sealed class UpdateProductRequest
{
    public string Name { get; init; } = string.Empty;
    public decimal Price { get; init; }
    public int StockQuantity { get; init; }
}

public async Task UpdateProductAsync(
    int productId,
    UpdateProductRequest request,
    AppDbContext context,
    CancellationToken cancellationToken)
{
    var product = await context.Products
        .SingleOrDefaultAsync(p => p.Id == productId, cancellationToken);

    if (product is null)
    {
        throw new KeyNotFoundException("Product was not found.");
    }

    product.Name = request.Name;
    product.Price = request.Price;
    product.StockQuantity = request.StockQuantity;

    await context.SaveChangesAsync(cancellationToken);
}

Only the Product returned by the query is tracked. EF Core detects the changes when SaveChanges runs, and the resulting SQL can update only the values that changed. No Attach or Update call is required.

If the DTO property names match the entity property names, CurrentValues.SetValues can copy the values:

var product = await context.Products
    .SingleOrDefaultAsync(p => p.Id == productId, cancellationToken);

if (product is null)
{
    throw new KeyNotFoundException();
}

context.Entry(product).CurrentValues.SetValues(request);
await context.SaveChangesAsync(cancellationToken);

This is convenient, but do not place client-controlled or protected properties in the DTO. Explicit assignment is often preferable when the update rules are complex.

Approach 3: Using Attach and Entry.State

What does Attach do?

Attach begins tracking an existing entity in the Unchanged state. By itself, it does not issue an update to the database.

var detachedProduct = new Product
{
    Id = 7,
    Name = "New product name",
    Price = 149.90m,
    StockQuantity = 25
};

context.Products.Attach(detachedProduct);
Console.WriteLine(context.Entry(detachedProduct).State); // Unchanged

After attaching, changing a property allows EF Core to detect the modification:

context.Products.Attach(detachedProduct);
detachedProduct.Price = 149.90m;
await context.SaveChangesAsync();

Although this can be valid for a simple entity, it becomes risky with graphs, navigation properties, missing values or untrusted client input. You should know exactly which objects are attached and which properties are intended to change.

Using Entry.State = Modified

If a detached entity represents a complete replacement and every updatable property should be written, you can set its state directly:

var detachedProduct = new Product
{
    Id = 7,
    Name = "New product name",
    Price = 149.90m,
    StockQuantity = 25
};

context.Entry(detachedProduct).State = EntityState.Modified;
await context.SaveChangesAsync();

This sets the state of that single Product entry. By contrast, context.Update(detachedProduct) can traverse an entity graph and change the states of related entities. Therefore, Entry.State may be more explicit when the operation is intentionally limited to one entity.

Both approaches have the same fundamental risk: a detached object may not contain the latest database values. An omitted property or a default value can overwrite data unintentionally. For partial updates, querying the current entity and assigning only allowed properties is generally safer.

Comparing update flows

FlowAdvantageRisk
Tracking query followed by UpdateAppears simpleCreates a duplicate tracking conflict for the same key
AsNoTracking followed by UpdateWorks with one detached instance and may use one read round-tripAll properties may be updated; missing values can overwrite data
Find or Single followed by property changesExplicit and usually safestRequires loading the current row
Attach plus StateProvides explicit state controlGraphs and property scope must be handled carefully

Common mistakes

  • Using a long-lived DbContext: Sharing one context across requests or unrelated operations allows the ChangeTracker to grow and makes duplicate instances more likely.
  • Automatically attaching every AsNoTracking result: This can be valid in selected scenarios, but it is often more complex than querying and modifying one tracked entity.
  • Using Update with a partial DTO: Properties missing from the DTO can be represented by default values and written back unexpectedly.
  • Updating client-provided navigation graphs: Update can mark related entities as Added or Modified in ways that were not intended.
  • Relying on Clear as the primary fix: ChangeTracker.Clear() can be useful in special cases, but it may conceal an incorrect context lifetime or update design.
  • Exposing entities instead of DTOs: DTOs define which fields can be changed and reduce overposting risks.

A practical diagnostic workflow

  1. Determine whether the update method already executed a tracking query with the same DbContext.
  2. Inspect context.ChangeTracker.Entries() for multiple instances of the same entity type and key.
  3. Print the entity state before updating: Detached, Unchanged or Modified.
  4. Do not call Attach or Update for an entity that was already loaded and is being tracked by the context.
  5. Choose one strategy: load and modify the existing entity, or update one detached instance without first querying it into the same context.
  6. Add rowversion or another optimistic-concurrency mechanism when overwriting another user's changes would be unacceptable.

Short practice exercise

Create a test method and complete the following tasks:

  1. Load the product with Id = 7 through a tracking query.
  2. Create a second Product with the same key and call Update to observe the exception.
  3. Change the read query to use AsNoTracking and verify that the conflict disappears.
  4. Implement a third version that loads the existing entity with SingleAsync and changes only its price.
  5. Inspect ChangeTracker.DebugView.LongView after each step.

Conclusion

Duplicate entity tracking is usually not random EF Core behavior. It is the result of combining two different objects with the same primary key inside one DbContext. The first step in solving the problem is to understand when each object becomes tracked.

AsNoTracking is valuable for read-only queries, but it is not a universal update solution. The safest general flow is to load the current entity in the update context, change only allowed properties and call SaveChanges. When detached updates are appropriate, understand the differences between Attach, Entry.State and Update, and account for missing properties, navigation graphs and concurrency.

With this approach, you do more than suppress a tracking exception: you build an update design that is diagnosable, predictable and maintainable in production.

Sources