In EF Core 10, how do you save a detached customer profile posted by a mobile app without rewriting every column?
answer
- Update marks every property
- Attach starts Unchanged
- Property(...).IsModified = true
- CurrentValues.SetValues(dto)
- one instance per key per context
basics
~20 sUpdate marks every property Modified, so the UPDATE rewrites all columns. To write less, Attach the object and set IsModified on the fields the endpoint owns, or load the row and copy the DTO with CurrentValues.SetValues, which marks only values that differ.
solid answer
~40 sThe mobile app's `Customer` arrives detached, so the context knows nothing about it. `db.Customers.Update(customer)` is one round trip but marks every non-key property `Modified`, so fields the app never sent overwrite good data with nulls. For a partial write without a read, `Attach(customer)` (which tracks it `Unchanged`) and then `Entry(customer).Property(c => c.Phone).IsModified = true` for each field the endpoint owns: the `UPDATE` sets only those columns. For the most precise write, load the tracked row with `FindAsync` and call `Entry(tracked).CurrentValues.SetValues(dto)`: only properties whose value actually differs are marked, at the cost of a second round trip. Never mix the two styles in one context - updating a posted instance after loading the same key throws an identity conflict.
code
csharp · 11 linesapp.MapPut("/customers/{id:int}", async (int id, CustomerProfileDto dto, CrmDbContext db) =>
{
var customer = await db.Customers.FindAsync(id);
if (customer is null) return Results.NotFound();
// copies matching property names; marks only values that differ
db.Entry(customer).CurrentValues.SetValues(dto);
await db.SaveChangesAsync();
return Results.NoContent();
});go deeper
Know that a posted object is not tracked, and that Update writes every column while a loaded entity writes only what changed.
Explain the three shapes - Update, Attach plus IsModified, and FindAsync plus SetValues - with their round trips, and why a context holds one instance per key.
Pick the shape from the endpoint contract: protect columns a client must never write, avoid overwriting omitted fields, and keep ownership checks from triggering an identity conflict.
Set a team rule for write endpoints - DTO plus SetValues by default, Update only for full-replace contracts - and weigh the extra read against data-loss risk.
## The problem: an entity the context has never seen A **detached** entity is an object EF Core is not tracking. In a CRM API, the mobile app sends a JSON customer profile; ASP.NET Core binds it to a `Customer` (or a DTO), and a fresh scoped `DbContext` handles the request. That context has no snapshot of the row, so it cannot know which fields the user changed. You have to tell EF Core what to write, and there are three standard ways to do it. ## Option 1 - Update: one round trip, every column `db.Customers.Update(customer)` starts tracking the object (and anything reachable from it) in the `Modified` state and marks **every property that may be saved** as modified. The key is not marked, because a key is never updated. - One round trip, no read. - The `UPDATE` sets every mapped column, whether or not the user touched it. - Original values are not known, so `OriginalValue` equals the current value. - A field the app did not send arrives as `null` or default and **overwrites** the stored value - the classic bug when a mobile client sends only the fields on its screen. - With generated keys, any object in the graph whose key is unset (`0`, `Guid.Empty`) is tracked as `Added` and inserted instead. You can carve exceptions out after the call: `db.Entry(customer).Property(c => c.CreatedAt).IsModified = false` removes that column from the `UPDATE`. ## Option 2 - Attach and mark what the endpoint owns `Attach` tracks the object as `Unchanged` (again `Added` for unset generated keys). Nothing is written until you mark properties: ```csharp db.Customers.Attach(customer); var entry = db.Entry(customer); entry.Property(c => c.Phone).IsModified = true; entry.Property(c => c.Email).IsModified = true; await db.SaveChangesAsync(); // UPDATE "Customers" SET "Phone" = @p0, "Email" = @p1 WHERE "Id" = @p2 ``` Setting `IsModified = true` on any property also moves the entity from `Unchanged` to `Modified`. This is the right shape for a PATCH-style endpoint whose contract says which fields it accepts. A variant from the EF Core docs attaches the posted object and then applies original values the client sent back (`entry.OriginalValues.SetValues(originalValues)`), so only differing properties are marked - precise, but it makes the client carry the old values. ## Option 3 - Load, then copy the incoming values ```csharp var tracked = await db.Customers.FindAsync(dto.Id); if (tracked is null) return Results.NotFound(); db.Entry(tracked).CurrentValues.SetValues(dto); await db.SaveChangesAsync(); ``` `SetValues` copies every property whose **name matches** an entity property - from an entity, a DTO or a dictionary - and marks a property modified **only if the new value differs** from the current one. If nothing changed, `SaveChanges` sends no `UPDATE` at all. - Two round trips: a `SELECT` and then the `UPDATE`. - Only real changes are written. - The DTO decides the field set; properties it does not declare are left alone, which is safer than binding the entity itself. ## Choosing between them | Approach | Round trips | Columns in the `UPDATE` | Risk | |---|---|---|---| | `Update` | 1 | all saveable columns | overwrites fields the client omitted | | `Attach` + `IsModified` | 1 | the ones you mark | the code must list the owned fields | | `FindAsync` + `SetValues` | 2 | only values that differ | an extra read per request | ## The identity-conflict trap A `DbContext` holds **at most one tracked instance per key**. If a handler first loads customer 42 (say, to check ownership) and then calls `Update(postedCustomer)` with key 42, EF Core throws an `InvalidOperationException`: "The instance of entity type 'Customer' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked." The fix is to pick one style - either query and apply changes to the tracked instance, or attach/update the posted one - never both in the same context. Two neighbouring concerns are deliberately outside this answer: detecting that another user changed the row in the meantime (a concurrency token), and how the batch of commands is sent and wrapped in a transaction.
- Why can Update insert a row instead of updating one?With generated keys, `Update` and `Attach` treat an entity whose key holds the CLR default (`0`, `Guid.Empty`) as new and track it `Added`. If the app posts a profile with `Id = 0`, or a new address in the graph without a key, `SaveChanges` sends an `INSERT` for it. For entity types without generated keys, `Update` always marks `Modified`.
- A handler loads customer 42 to check ownership and then calls Update on the posted customer 42. What happens?`Update` throws an `InvalidOperationException` because the context already tracks another instance with the same key. A context keeps one instance per key. Either apply the posted values to the loaded instance with `CurrentValues.SetValues`, or check ownership with a query that does not track (for example a projection to a bool) before calling `Update`.
- What does setting IsModified to false do on a property of a queried entity that the code has edited?It unmarks the property and, for a tracked entity with an original value, resets the current value to that original, so the edit is discarded rather than written. If it was the last modified property, the entity drops back from `Modified` to `Unchanged`.
- Update compares the posted values with the database and writes only the differences.
- Attach marks the object Modified, so SaveChanges rewrites every column.
- CurrentValues.SetValues marks every matching property modified even when the value is unchanged.
- Loading a row and then calling Update with a posted copy of it is harmless.
- Attach always tracks an object Unchanged, even when its generated key is 0.