ASP.NET Core Web API Interview Question #120
What is optimistic concurrency in EF Core?
Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate
Quick Interview Answer
Optimistic concurrency assumes conflicts are uncommon and detects whether data changed between reading and saving. A concurrency token such as SQL Server rowversion can be checked when EF Core performs an update.
Detailed Explanation
Optimistic concurrency assumes conflicts are uncommon and detects whether data changed between reading and saving. A concurrency token such as SQL Server rowversion can be checked when EF Core performs an update.
If another transaction has changed the row, SaveChangesAsync can throw DbUpdateConcurrencyException. The API must then apply a deliberate conflict strategy rather than silently overwriting newer data.
Code Example
public class Product
{
public int Id { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; } = [];
}
try
{
await _db.SaveChangesAsync(token);
}
catch (DbUpdateConcurrencyException)
{
return Conflict();
}