C# Interview Question #179

What is optimistic concurrency in EF Core?

EF Core, Data Access & Performance Senior Advanced

Quick Interview Answer

Optimistic concurrency assumes that conflicts are relatively uncommon and allows multiple users to read data without locking it for the duration of their work.

Detailed Explanation

Optimistic concurrency assumes that conflicts are relatively uncommon and allows multiple users to read data without locking it for the duration of their work.

A concurrency token, such as SQL Server rowversion, can be used to detect whether a row changed after it was originally read. EF Core then throws DbUpdateConcurrencyException when an update affects no row because the concurrency token no longer matches.

The application must decide how to resolve the conflict: reject the update, reload current values, merge changes, or ask the user to retry.

Code Example

public class Product
{
    public int Id { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; } = Array.Empty<byte>();
}