📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

In an ASP.NET Core API you receive an entity that was not loaded by this DbContext. When would you use Attach, Update or Add for it? Why does Update mark every column as modified, and what better approaches are there for disconnected updates?

Covers EF Core disconnected-entity handling: how Add, Attach and Update set states across a graph based on key values, why Update writes every column, the over-posting and lost-update risks, and better patterns: load-and-apply, CurrentValues.SetValues, marking specific properties, ExecuteUpdate and concurrency tokens.

Mid-Level Theory Intermediate aspnet-core attach change-tracking concurrency disconnected-entities ef-core

🎯 Key points

  • Add: whole graph Added → INSERTs
  • Attach: entities with a key value become Unchanged, without one become Added (generated keys)
  • Update: entities with a key value become Modified with every property marked → UPDATE of all columns
  • Update has no original values, so it overwrites concurrent edits and posted-over fields (over-posting)
  • Load tracked, apply the DTO (manually or CurrentValues.SetValues), let DetectChanges find real changes
  • Attach + Property(p).IsModified = true for a known partial update without a read
  • ExecuteUpdate for set-based or single-column changes without loading
  • Carry a RowVersion and set its OriginalValue so stale writes throw DbUpdateConcurrencyException → 409

⏱ 30-second answer

All three walk the whole graph and set states based on whether each entity has a key value:

  • Add: everything becomes Added, so EF Core inserts it.
  • Attach: entities with a key become Unchanged, without one become Added. Nothing is written until you change something.
  • Update: entities with a key become Modified with every property marked, because EF Core has no original values to compare with, so it writes every column.

That makes Update dangerous for APIs: it overwrites columns the client never meant to change and silently loses concurrent edits. Better: accept a use-case DTO containing only the editable fields (so nothing can be over-posted), load the entity tracked and apply the DTO so only real changes are written, use Attach plus IsModified for a known partial update, or ExecuteUpdate for set-based changes, always with a RowVersion set as the original value. The trade-off is one extra read in exchange for correct, minimal updates.

🗣 Full answer (senior)

How I would answer this in an interview

"A disconnected entity is one the current context didn't load, typically something rebuilt from a request body. EF Core has no snapshot for it, so I have to tell it the state. Add, Attach and Update all traverse the graph from the object I pass, and for each entity they look at the key: no key value with a store-generated key means it must be new, so it's Added. With a key value, Add still says Added, Attach says Unchanged, and Update says Modified. The important part is that Update marks every property modified, because without original values EF Core can't know which ones changed. So the SQL is an UPDATE that sets every column.

That causes two real problems. First, over-posting and partial DTOs: if the client didn't send CreditLimit, it's default on my object and I've just written zero over a real value. Second, lost updates: two users edit different fields, and the second save writes the first user's fields back to their old values. For example, at [company] we had [an admin screen] where [support notes were disappearing] because the endpoint mapped the DTO onto a new entity and called Update(); switching to load-and-apply with a row version stopped it, and [the 409 rate showed how often it had been happening, about N a week].

So my default for an API update is: load the entity with a tracking query, check the row version, apply only the fields the DTO is allowed to change, and save. DetectChanges then writes only the columns that actually changed. If the read really matters, for example a hot path that flips one flag, I Attach a stub with the key and row version and mark just that property modified, or use ExecuteUpdate. The mistake I see is Update() used as the default 'save this' method. It is a blunt instrument; one extra indexed read is almost always cheaper than a corrupted row."


What each method does to a graph

Method Entity with a key value Entity without a key value (generated key) SQL
Add Added Added INSERT (fails on duplicate key)
Attach Unchanged Added Nothing until a change is made
Update Modified, all properties Added UPDATE every column
Remove Deleted — DELETE

Choosing an approach

Approach When it fits Cost Risk
Load tracked, apply DTO Default for API updates One indexed read Lowest; only changed columns written
Entry(e).CurrentValues.SetValues(dto) DTO property names match the entity Same read Copies every matching property, so the DTO must only contain editable fields
Attach + IsModified Hot path, known small change No read You must supply the key and row version correctly
ExecuteUpdate Set-based or single-column changes No read, no tracker Bypasses SaveChanges interceptors and domain logic
Update() Whole-object replace where the client owns every field (rare) No read Overwrites everything, lost updates

Production example

After replacing Update() with load-and-apply plus a RowVersion check on [the customer profile endpoint], the UPDATE statements went from [~40 columns] to [usually 1–3], the transaction log volume for that table dropped by [~70%], and the API started returning [a handful of] 409s a day that had previously been silent overwrites.

🔍 What the interviewer is checking

Checks that the candidate understands disconnected entities, what Add/Attach/Update really do, and how to update safely in an API.

Green flags

  • Explains the key-based state rules for each method across the graph.
  • Explains why Update writes every column (no original values).
  • Raises over-posting and lost updates, and uses a RowVersion original value.
  • Offers load-and-apply, IsModified and ExecuteUpdate with trade-offs.

Red flags

  • Uses Update() for every write.
  • Maps request DTOs straight onto entities with all properties.
  • Sets the row version as the current value, or has no concurrency check.

📚 Learn in depth

1. Why a disconnected entity has no history

Request 1: context A loads Customer 7 -> snapshot -> DTO -> JSON -> client
           context A disposed, snapshot gone
Request 2: JSON -> DTO -> new Customer { Id = 7, ... }
           context B has never seen Customer 7

Context B has no original values, so it cannot work out what changed. You either give it the original values (by loading) or tell it what changed (by marking properties).

2. How the graph is walked

Add, Attach, Update and Remove use the same traversal: start at the root, follow every navigation to reachable entities that are not already tracked, and decide each entity's state. The key test (IsKeySet) is what separates new from existing when keys are store-generated. With client-generated keys (Guid.CreateVersion7() set in the constructor) every entity has a key, so Attach and Update cannot tell new from existing, and you must decide yourself (or use TrackGraph).

3. The SQL difference

db.Update(new Customer { Id = 7, Name = "Ana", RowVersion = rv });
UPDATE [Customers] SET [Name] = @p0, [Email] = @p1, [CreditLimit] = @p2,
       [Notes] = @p3, [CreatedAt] = @p4  -- every mapped column, defaults included
OUTPUT INSERTED.[RowVersion]
WHERE [Id] = @p5 AND [RowVersion] = @p6;

Compare with load-and-apply where only Name changed:

UPDATE [Customers] SET [Name] = @p0
OUTPUT INSERTED.[RowVersion]
WHERE [Id] = @p1 AND [RowVersion] = @p2;

4. Concurrency across the disconnect

A [Timestamp] RowVersion column is generated by SQL Server on every write. Send it to the client with the DTO, receive it back, and set it as the original value of the tracked entity:

db.Entry(customer).Property(c => c.RowVersion).OriginalValue = dto.RowVersion;

EF Core puts the original value in the WHERE clause. Zero rows affected means someone else changed the row, and SaveChanges throws DbUpdateConcurrencyException, which an API maps to 409 Conflict. Setting it on the current value does nothing useful, which is a very common bug.

5. Collections in disconnected graphs

Updating an order with its lines is harder: some lines are new, some changed, some removed. Load the order with Include(o => o.Lines), then reconcile: update matching lines, add new ones, remove missing ones. EF Core deletes orphaned required dependants automatically when they are removed from the collection.

Try it yourself

  1. Call Update on a stub entity and log the SQL; then load-and-apply the same change and compare.
  2. Post a DTO that omits a field and watch Update overwrite it with the default.
  3. Add a [Timestamp] property, set OriginalValue from a stale value and catch DbUpdateConcurrencyException.
  4. Attach a stub, mark one property modified and confirm a one-column UPDATE.
  5. Use client-generated Guid keys and observe that Attach marks a genuinely new entity Unchanged.

💻 Code

Three ways to handle a PUT, from safest to cheapest.

namespace Shop.Customers;

using Microsoft.EntityFrameworkCore;

public sealed record UpdateCustomerRequest(string Name, string Email, byte[] RowVersion);

public sealed class CustomerUpdates(ShopDbContext db)
{
    // 1. Default: load tracked, check concurrency, apply only editable fields.
    public async Task<bool> UpdateAsync(int id, UpdateCustomerRequest req, CancellationToken ct)
    {
        var customer = await db.Customers.SingleOrDefaultAsync(c => c.Id == id, ct);
        if (customer is null) return false;

        // The client's row version becomes the ORIGINAL value, so it goes in the WHERE clause.
        db.Entry(customer).Property(c => c.RowVersion).OriginalValue = req.RowVersion;

        customer.Name = req.Name;     // explicit mapping: CreditLimit can never be over-posted
        customer.Email = req.Email;

        await db.SaveChangesAsync(ct); // UPDATE only changed columns; throws DbUpdateConcurrencyException if stale
        return true;
    }

    // 2. No read: attach a stub and mark exactly one property.
    public async Task DeactivateAsync(int id, byte[] rowVersion, CancellationToken ct)
    {
        var stub = new Customer { Id = id, RowVersion = rowVersion };
        db.Customers.Attach(stub);                               // Unchanged
        stub.IsActive = false;
        db.Entry(stub).Property(c => c.IsActive).IsModified = true;
        await db.SaveChangesAsync(ct);                           // UPDATE [Customers] SET [IsActive] = @p0 WHERE Id AND RowVersion
    }

    // 3. Set-based, bypasses the change tracker (and SaveChanges interceptors).
    public Task<int> DeactivateDormantAsync(DateTimeOffset cutoff, CancellationToken ct) =>
        db.Customers
          .Where(c => c.LastOrderAt < cutoff && c.IsActive)
          .ExecuteUpdateAsync(s => s.SetProperty(c => c.IsActive, false), ct);
}
// Endpoint: map the concurrency failure to 409.
app.MapPut("/customers/{id:int}", async (int id, UpdateCustomerRequest req, CustomerUpdates svc, CancellationToken ct) =>
{
    try
    {
        return await svc.UpdateAsync(id, req, ct) ? Results.NoContent() : Results.NotFound();
    }
    catch (DbUpdateConcurrencyException)
    {
        return Results.Problem("The customer was changed by someone else. Reload and try again.", statusCode: 409);
    }
});

⚠ Common mistakes

  • Mistake: Using Update() as the default save for API PUTs. Why it is wrong: it writes every column, so missing DTO fields overwrite real data and concurrent edits are lost. Instead: load tracked and apply only editable fields.
  • Mistake: Mapping the request DTO onto the entity with CurrentValues.SetValues(dto) where the DTO has extra properties. Why it is wrong: any matching property is copied, enabling over-posting (for example IsAdmin or CreditLimit). Instead: a DTO per use case with only editable fields, or explicit assignments.
  • Mistake: Setting the client's RowVersion as the current value. Why it is wrong: EF Core uses the original value in the WHERE clause, so the check compares against the freshly loaded version and always passes. Instead: set Property(p => p.RowVersion).OriginalValue.
  • Mistake: Calling Attach on a graph with client-generated keys and expecting new children to be inserted. Why it is wrong: every entity has a key, so all become Unchanged and nothing is inserted. Instead: use TrackGraph or decide states explicitly.
  • Mistake: Attaching an entity whose key is already tracked in the same context. Why it is wrong: it throws "another instance with the same key value is already being tracked". Instead: load once, or check Local first.
  • Mistake: Using ExecuteUpdate where audit or soft-delete logic lives in a SaveChangesInterceptor. Why it is wrong: ExecuteUpdate bypasses SaveChanges, so the audit columns are not set. Instead: set them in the ExecuteUpdate call or keep that path on SaveChanges.
  • Mistake: Replacing a child collection wholesale on a disconnected graph. Why it is wrong: EF Core cannot tell which children were removed, so rows are left behind or keys clash. Instead: load with Include and reconcile adds, updates and removes.

🏛 Senior insight: trade-offs

I treat Update() as a code-review flag. Not banned, but it needs a reason, usually a whole-resource replace where the client really owns every field and there is a concurrency token. The default in our APIs is load, check the row version, apply, save. The extra read is a clustered-index seek of a millisecond or two; the bug it prevents, silently corrupted data, is the expensive kind that shows up weeks later in a support ticket.

Approach When it fits Cost When not to
Load + apply + RowVersion Most PUT/PATCH endpoints One read Extreme hot paths
Attach stub + IsModified Toggling a known field at high volume Must carry key and row version Changes that need domain validation of current state
ExecuteUpdate Bulk or single-column, no domain logic Skips tracker and interceptors When audit relies on SaveChanges
Update() Full replace, client owns all fields, with concurrency token Writes every column Partial DTOs, shared records

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Update() writing all columns. Why: Checks the narrower question of the cost and risk of Update() on disconnected entities.
    How to answer

    Update() attaches the entity graph and marks every property Modified, because EF Core has no snapshot of original values to compare against, so it can't tell which properties actually changed. It sends all columns, which silently overwrites (loses) other users' concurrent edits and wastes I/O. Instead: load the entity tracked and apply the DTO's changes (only changed columns are written); or attach and set Entry(e).Property(x => x.Name).IsModified = true for specific fields; or use ExecuteUpdate for set-based changes in one statement without loading. Always add a RowVersion concurrency token ([Timestamp] byte[]): EF Core adds it to the WHERE clause and throws DbUpdateConcurrencyException if someone else changed the row, which you turn into a 409.

  2. When: Candidate mentions over-posting or mapping a DTO onto an entity. Why: Checks the design reasons to keep DTOs and domain entities separate.
    How to answer

    A domain model represents business concepts with behaviour and invariants (an Order that can be paid, cancelled, and refuses invalid changes). A DTO (data transfer object) is a flat, behaviour-free contract for moving data across a boundary: an HTTP request or response, a message, a query result. Keep them separate so that the API contract and the domain can change independently, so clients cannot over-post fields they must not set (IsAdmin, Status), and so internal data does not leak in responses. Map with explicit code, source-generated mappers (Mapperly) or EF Core projections straight to DTOs for reads. Sharing one type is acceptable only for simple CRUD with no rules, and even then be careful at public boundaries.

  3. When: Candidate mentions marking individual properties modified or setting original values. Why: Checks fluency with the Entry API used for disconnected updates.
    How to answer

    db.Entry(entity) returns an EntityEntry<T>, the change tracker's view of one entity:

    • State, CurrentValues, OriginalValues and GetDatabaseValuesAsync() for state and values.
    • Property(p => p.X) gives CurrentValue, OriginalValue and IsModified, so you can mark one column for update, or set the RowVersion original value for a concurrency check.
    • Collection(...)/Reference(...) give explicit loading (LoadAsync, IsLoaded) and Query() to filter or count related rows without loading them all.
    • CurrentValues.SetValues(dto) copies matching values; ReloadAsync() discards local changes.

    For disconnected graphs, ChangeTracker.TrackGraph visits each node so you choose its state. The trade-off: it gives precise control, but it is easy to misuse (setting current instead of original values, or calling Entry() in hot loops).

🛠 Real-world problems: how you handle them

Support notes vanishing after Update() on a disconnected customer
Situation
A [B2B ordering] platform on Azure SQL in Australia East; [~30] support staff edit customer records through an admin SPA. The PUT endpoint built a `Customer` from the request DTO and called `db.Update(customer)`.
Signals
Support tickets that [notes and credit limits] were reverting; no errors in Application Insights; audit triggers showed full-row updates where only one field had been edited in the UI.
Investigation
Enabled `LogTo` with `EnableSensitiveDataLogging` in a non-production environment and saw the UPDATE setting all [40] columns. Reproduced with two browser sessions editing different fields of the same customer: the second save restored the first session's fields. Checked the DTO: it omitted `CreditLimit`, so `Update` wrote `0`.
Resolution
Immediately: removed `CreditLimit` from the entity mapping for that endpoint by loading tracked and assigning only the DTO's fields. Then added a `[Timestamp] RowVersion` column (migration with no downtime), returned it with every GET, set it as the original value on PUT and mapped `DbUpdateConcurrencyException` to 409 with a reload prompt in the SPA.
Prevention
Integration test that edits two fields concurrently and expects a 409; code-review checklist item flagging `Update(` and `State = EntityState.Modified`; DTOs per use case with only editable fields; a dashboard of 409s per endpoint.

How to tell it (STAR)

**S:** At [company], support staff reported that [customer notes and credit limits] kept reverting after edits in our admin tool. **T:** I was asked to find the cause because there were no errors anywhere. **A:** I logged the SQL in a test environment and saw every update writing all [40] columns, then reproduced it with two browser sessions: the second save silently restored the first user's changes. The endpoint was calling `Update()` on an entity built from the request. I changed it to load the customer tracked, apply only the editable fields, and check a new `RowVersion` column, returning 409 when it was stale. **R:** The reverting-data tickets stopped [within a week], UPDATEs dropped to [one to three] columns, and we found the conflicts had been happening [about N times a week] without anyone knowing.

↩ Usually asked after

More in Change Tracking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me