Interview frequency: …
Short answer
Add a [Timestamp] byte[] RowVersion property; an update is rejected with DbUpdateConcurrencyException if another user changed the row since it was read.
Explanation
Optimistic Concurrency does not hold database locks while a user reads data. A RowVersion column (or xmin in PostgreSQL) automatically gets a new binary value whenever the row changes. On save, EF Core issues UPDATE ... WHERE Id = @id AND RowVersion = @originalRowVersion. If the value changed, no row is updated and EF Core throws a concurrency exception, letting you merge changes or notify the user.
Code example
public class BankAccount {
public int Id { get; set; }
public decimal Balance { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; } = null!;
}Common mistakes
- Ignoring DbUpdateConcurrencyException, losing user changes or overwriting them blindly (Blind Overwrite).