Interview question
Update one property without loading the entity
Attaches a key-only stub and marks one property modified for a narrow update while naming the rules this pattern bypasses.
TL;DR
Attaches a key-only stub and marks one property modified for a narrow update while naming the rules this pattern bypasses.
Attach semantics, property-level modification, affected-row behavior, validation boundaries, and safe use of targeted updates.
Practice the problem like a real interview: restate, reason, implement, and test.
An internal admin command changes only Order.InternalNote by id. The field has already passed authorization and validation, and no existing order state is needed to enforce the rule. Avoid an initial select. Return not found if no row is updated.
Next in EF Core Labs: Order Plus Outbox
The generated SQL updates only InternalNote for the requested id. If the id does not exist, EF reports a concurrency-style zero-row result and the method returns not found.
I attach a stub containing only the key, assign the allowed field, and mark that property modified. EF then generates a narrow update. This is not a default replacement for loading aggregates; it is a deliberate optimization for a command whose invariant can be enforced without current entity state.
public static async Task<bool> UpdateInternalNoteAsync(
AppDbContext db,
Guid orderId,
string note,
CancellationToken cancellationToken)
{
var order = new Order { Id = orderId };
db.Attach(order);
order.InternalNote = note.Trim();
db.Entry(order)
.Property(candidate => candidate.InternalNote)
.IsModified = true;
try
{
await db.SaveChangesAsync(cancellationToken);
return true;
}
catch (DbUpdateConcurrencyException)
{
return false;
}
}
The database receives one narrow update and no preceding select. EF expects one affected row and can surface a zero-row update as DbUpdateConcurrencyException. If the model has required concurrency tokens, those original values must also be supplied or this pattern should not be used.
Spot a weak answer, missing edge case, or clearer explanation? Send it in.