Entity Framework Core Interview Question #109

Why can blindly calling Update on a disconnected entity be risky?

Change Tracking, Updates, Transactions & Concurrency Mid-Level Intermediate

Quick Interview Answer

Update generally marks the entity and appropriate reachable graph members as modified. With client-supplied models, this can cause more columns or related entities to be updated than intended.

Detailed Explanation

Update generally marks the entity and appropriate reachable graph members as modified. With client-supplied models, this can cause more columns or related entities to be updated than intended.

It can also contribute to overposting, where a client changes properties that were not supposed to be editable.

A safer pattern is often to load the existing entity, validate authorization and input, then copy only permitted fields before saving.

Code Example

var existing = await db.Products.FindAsync(dto.Id);

existing!.Name = dto.Name;
existing.Price = dto.Price;
// Do not copy protected fields from the client.

await db.SaveChangesAsync();