What are best practices for EF Core updates, transactions, and concurrency?
Quick Interview Answer
Detailed Explanation
Use tracked entities for straightforward unit-of-work updates, but use no-tracking queries for read-only workloads. In disconnected web requests, load the authoritative entity and map only permitted changes instead of blindly updating client-supplied graphs.
Use ExecuteUpdate and ExecuteDelete for appropriate set-based operations, while remembering that they bypass normal tracked-entity SaveChanges behavior. Keep transactions short, rely on a single SaveChanges transaction when sufficient, and introduce explicit transactions only when the business operation requires a wider database boundary.
Use optimistic concurrency tokens for data that can be edited concurrently and handle conflicts according to business rules. For workflows crossing database and external-service boundaries, design for partial failure with patterns such as idempotency, durable messaging, and the outbox pattern.
Code Example
var product = await db.Products
.SingleOrDefaultAsync(
p => p.Id == dto.Id,
cancellationToken);
if (product is null)
return;
product.Name = dto.Name;
product.Price = dto.Price;
try
{
await db.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateConcurrencyException)
{
// Apply the application's conflict-resolution policy.
throw;
}