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.
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.
"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,AttachandUpdateall 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,Addstill says Added,Attachsays Unchanged, andUpdatesays Modified. The important part is thatUpdatemarks 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 calledUpdate(); 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.
DetectChangesthen writes only the columns that actually changed. If the read really matters, for example a hot path that flips one flag, IAttacha stub with the key and row version and mark just that property modified, or useExecuteUpdate. The mistake I see isUpdate()used as the default 'save this' method. It is a blunt instrument; one extra indexed read is almost always cheaper than a corrupted row."
| 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 |
| 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 |
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.
Checks that the candidate understands disconnected entities, what Add/Attach/Update really do, and how to update safely in an API.
Green flags
Update writes every column (no original values).RowVersion original value.IsModified and ExecuteUpdate with trade-offs.Red flags
Update() for every write.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).
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).
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;
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.
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.
Update on a stub entity and log the SQL; then load-and-apply the same change and compare.Update overwrite it with the default.[Timestamp] property, set OriginalValue from a stale value and catch DbUpdateConcurrencyException.Attach a stub, mark one property modified and confirm a one-column UPDATE.Guid keys and observe that Attach marks a genuinely new entity Unchanged.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);
}
});
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.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.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.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.Local first.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.Include and reconcile adds, updates and removes.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 |
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.
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.
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).
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.
Last updated 23 Nov 2026.