Loading…
Loading…
10 карточек
How do you implement optimistic concurrency in EF Core?
нажми, чтобы перевернуть
SQL Server: [Timestamp] byte[] RowVersion — auto-incremented. PostgreSQL: xmin system column. EF generates: UPDATE ... WHERE Id = @id AND RowVersion = @old. If 0 rows affected -> DbUpdateConcurrencyException. Handling: re-read the entity, merge changes, retry. Pessimistic locking: SELECT ... FOR UPDATE — via raw SQL.
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int Stock { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; } = null!;
}
// Usage
try
{
product.Stock -= quantity;
await context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
// Someone else modified the record — re-read and retry
var entry = ex.Entries.Single();
await entry.ReloadAsync();
// merge logic...
}Когда да
Concurrent edits to the same record: cart, profile, inventory. Instead of distributed locks
Когда нет
Write-only (append) operations. If conflicts are extremely rare — the RowVersion overhead is not justified
Совет на собеседовании
Optimistic concurrency is the default for web apps. Pessimistic (FOR UPDATE) is for financial operations.
Свайп вправо — знаю, влево — не знаю
