LESSON 4 OF 19

Why Does an Update Disappear When AsNoTracking Is Used Incorrectly?

Learn why entities loaded with AsNoTracking are not updated automatically, how detached updates work, and how to safely map API DTOs to tracked entities.

25 dk 109

Introduction

When working with Entity Framework Core, developers often use AsNoTracking() to reduce the overhead of change tracking. However, this method also means that the entity instances returned by the query are not tracked by the current DbContext. As a result, changing a property in memory does not automatically produce a database update when SaveChangesAsync() is called.

This behavior is not a bug. It is part of the intended Entity Framework Core model. The problem usually appears when an approach created for read-only queries is copied into an update operation. If a query contains AsNoTracking() and the returned object is later modified without being attached or marked as modified, the application changes the object in memory but no database row is updated.

In this lesson, we will examine the difference between tracking and no-tracking queries, understand detached entities, compare several update strategies, and map data from a web API DTO to an entity safely.

For detailed information about EF Core change tracking, see the Microsoft Learn Change Tracking documentation.

The fundamental difference between tracking and AsNoTracking

By default, Entity Framework Core tracks entity results returned from normal queries. For example:

var product = await dbContext.Products
    .SingleAsync(p => p.Id == productId);

product.Price = 149.99m;
await dbContext.SaveChangesAsync();

In this example, EF Core begins tracking product when it is queried. When the Price property changes, EF Core detects the modification and generates an appropriate UPDATE statement during SaveChangesAsync().

For a read-only query, disabling tracking can be appropriate:

var products = await dbContext.Products
    .AsNoTracking()
    .Where(p => p.IsActive)
    .Select(p => new ProductListItemDto
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .ToListAsync();

Tracking is unnecessary here because the results are used only for display. Projecting into a DTO also ensures that the API sends only the fields required by the client.

Seeing why the update disappears

The following code may look correct at first:

var product = await dbContext.Products
    .AsNoTracking()
    .SingleAsync(p => p.Id == productId);

product.Price = 199.99m;
await dbContext.SaveChangesAsync();

However, product is not being tracked by the context, so SaveChangesAsync() has no detected modification to persist. The save operation may complete without throwing an exception, but the number of updated database rows remains zero.

You can diagnose this by inspecting the entity state:

var product = await dbContext.Products
    .AsNoTracking()
    .SingleAsync(p => p.Id == productId);

product.Price = 199.99m;

Console.WriteLine(dbContext.Entry(product).State);
await dbContext.SaveChangesAsync();

The state will generally be Detached. A detached entity is an entity that is not currently tracked by the context. EF Core cannot automatically determine which properties changed or whether the object should be inserted, updated, or deleted.

Solution 1: Use tracking for update operations

If the entity is queried and updated within the same unit of work, the simplest solution is not to use AsNoTracking():

public async Task<bool> IncreasePriceAsync(int productId, decimal newPrice)
{
    var product = await dbContext.Products
        .SingleOrDefaultAsync(p => p.Id == productId);

    if (product is null)
    {
        return false;
    }

    product.Price = newPrice;
    await dbContext.SaveChangesAsync();
    return true;
}

EF Core tracks the entity in this version and can detect the changed property. For a small, clearly scoped unit of work, this is usually the easiest approach to understand and maintain.

Tracking queries also provide identity resolution. When the same entity key is encountered again within the same context, EF Core can reuse the already tracked instance instead of creating another instance. This helps avoid conflicts caused by two different objects representing the same database row.

Solution 2: Explicitly update a detached entity

If the entity comes from another application layer, another DbContext, or a client request, it should be treated as detached. You can explicitly attach it:

var product = new Product
{
    Id = productId,
    Price = 199.99m
};

dbContext.Products.Attach(product);
dbContext.Entry(product).Property(p => p.Price).IsModified = true;

await dbContext.SaveChangesAsync();

Attach places the entity in the context with an initial state of Unchanged. The Price property is then marked as modified. EF Core can therefore generate an update for that property without changing the other columns.

You can also use Update:

dbContext.Products.Update(product);
await dbContext.SaveChangesAsync();

When Update is used, the entity and potentially its graph are treated as modified. This may be acceptable when the client sends a complete, trusted representation of the entity. For partial updates, sensitive fields, or large entities, explicitly marking only the changed properties is usually more controlled.

Solution 3: Load a tracked entity and apply DTO values

In web API applications, a recommended pattern is to accept a DTO from the client and load the database entity as a tracked instance before applying allowed values.

public sealed class UpdateProductDto
{
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
}

public async Task<bool> UpdateProductAsync(
    int productId,
    UpdateProductDto dto)
{
    var product = await dbContext.Products
        .SingleOrDefaultAsync(p => p.Id == productId);

    if (product is null)
    {
        return false;
    }

    product.Name = dto.Name;
    product.Price = dto.Price;

    await dbContext.SaveChangesAsync();
    return true;
}

The client does not send an entity that is attached blindly to the context. Instead, the server loads the existing entity, validates the request, and copies only the permitted DTO fields. This prevents clients from modifying fields such as CreatedAt, IsDeleted, ownership identifiers, or other security-sensitive values.

This pattern also gives the application a place to enforce business rules. For example, the service can verify that the product is not deleted, that the current user is authorized, and that the new price is valid before saving.

An incorrect DTO update

The following code may appear reasonable, but the update can disappear:

var product = await dbContext.Products
    .AsNoTracking()
    .SingleAsync(p => p.Id == productId);

product.Name = dto.Name;
product.Price = dto.Price;

await dbContext.SaveChangesAsync();

The problem is not the DTO. The problem is that DTO values are copied into a detached entity, and that entity is never attached or marked as modified. Fix the code either by loading the entity with tracking or by explicitly attaching the detached instance and defining its state.

Combining AsNoTracking with projection

For lists, reports, and read-only API responses, projecting directly to a DTO is often the clearest option:

var result = await dbContext.Products
    .AsNoTracking()
    .Where(p => p.IsActive)
    .Select(p => new ProductSummaryDto
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .ToListAsync();

The returned objects should not be treated as entities to update. If a user wants to edit a product, the client can call a separate update endpoint with the product identifier and editable fields. The server then reloads the entity, validates the DTO, and saves the changes through a tracked instance.

Common mistakes

  • Adding AsNoTracking to every query: It is useful for read-only operations but can disable automatic change detection in update workflows.
  • Assuming a successful SaveChanges means a row was updated: No exception only means that the operation completed; the context may have had no tracked changes.
  • Calling SaveChanges on a detached entity: Objects that are not connected to the context are not automatically persisted.
  • Calling Update directly on client-supplied entities: The client may change fields that should be controlled by the server. DTOs and explicit mapping are safer.
  • Attaching two objects with the same key: A tracking conflict can occur if the context already tracks another instance with that key.
  • Treating AsNoTracking as a transaction or concurrency solution: No-tracking changes change detection only; it does not solve authorization, concurrency, or transaction management.

A practical decision guide

  1. Is the query used only for display, reporting, or producing an API response? If yes, use AsNoTracking() with DTO projection.
  2. Will the entity be queried and modified within the same context? If yes, use a tracking query.
  3. Did the entity come from another context or a client request? If yes, treat it as detached.
  4. Can the client update only selected fields? If yes, load the entity with tracking and copy only allowed DTO values.
  5. Is no-tracking needed for a specific performance reason, but an update is still required? If yes, use Attach with explicit property state or evaluate a direct update approach separately.

Short practice exercise

Write a service method that updates a Product entity using an UpdateProductDto. The method should return false when the product does not exist and should update only the Name and Price properties.

  1. Write a first version that accidentally uses AsNoTracking().
  2. Inspect dbContext.Entry(product).State after changing the object and explain why the database is not updated.
  3. Fix the first version by removing AsNoTracking().
  4. Write a second fix using Attach and mark only the two editable properties as modified.
  5. Inspect the generated SQL and compare which columns are updated by the two solutions.

Conclusion

AsNoTracking() is not an alternative update mechanism. It is an optimization for queries that do not need change tracking. When an entity is loaded with no tracking, EF Core does not automatically monitor changes made to that object. Therefore, calling SaveChangesAsync() alone is not enough.

The safest general update pattern is to load the existing entity with tracking and copy validated DTO values into it. For detached scenarios, use Attach, Update, or property-level state management deliberately. The core rule is simple: Use AsNoTracking for read-only work, and use tracking or explicit state management when changes must be persisted.

Sources