Transactions and isolation levels in EF Core
SaveChangesAsync() - a default transaction "for free"
_context.Orders.Add(newOrder);
_context.Customers.Update(customer);
await _context.SaveChangesAsync();
// EF Core AUTOMATICALLY wraps ALL the changes from this call in ONE SQL transaction
// If ANYTHING fails - EVERYTHING is rolled back, nothing is partially saved
This is an important fact - you don't have to manage a transaction by hand for a single SaveChangesAsync(), even if you modify many different tables at once - EF Core does it automatically.
When you need an explicit transaction - multiple SaveChangesAsync() calls in one operation
public async Task TransferFundsAsync(int fromAccountId, int toAccountId, decimal amount)
{
using var transaction = await _context.Database.BeginTransactionAsync();
try
{
var fromAccount = await _context.Accounts.FindAsync(fromAccountId);
fromAccount.Balance -= amount;
await _context.SaveChangesAsync(); // pierwszy zapis
var toAccount = await _context.Accounts.FindAsync(toAccountId);
toAccount.Balance += amount;
await _context.SaveChangesAsync(); // drugi zapis
await transaction.CommitAsync(); // OBA zapisy zatwierdzone RAZEM
}
catch
{
await transaction.RollbackAsync(); // BOTH writes are rolled back if anything fails
throw;
}
}
Without an explicit transaction, if the second SaveChangesAsync() failed (e.g. a network error to the database), the first write would already have been saved - the source account would have the money deducted, and the target one wouldn't receive it. An explicit transaction guarantees the atomicity of the whole operation.
Savepoints - a partial rollback inside a transaction
using var transaction = await _context.Database.BeginTransactionAsync();
await _context.SaveChangesAsync(); // pierwsza operacja
await transaction.CreateSavepointAsync("AfterFirstStep");
try
{
await SomeRiskyOperationAsync(); // e.g. a call to an external service
await _context.SaveChangesAsync();
}
catch
{
await transaction.RollbackToSavepointAsync("AfterFirstStep"); // roll back ONLY the risky part
// pierwsza operacja NADAL jest zachowana w transakcji
}
await transaction.CommitAsync();
This is useful when one transaction has several stages, only some of which are risky - you don't have to roll everything back, only the part after the last safe point.
Transaction isolation levels (Isolation Levels)
using var transaction = await _context.Database.BeginTransactionAsync(IsolationLevel.Serializable);
| Level | What it guarantees | Performance cost |
|---|---|---|
ReadUncommitted |
Can read uncommitted changes of other transactions ("dirty read") | Lowest |
ReadCommitted (the default in SQL Server) |
Reads only committed data, but it may change between reads within the same transaction | Low |
RepeatableRead |
The same rows give the same result when read repeatedly within a transaction | Medium |
Serializable |
Full isolation - transactions behave as if they ran one after another | Highest (the most locks, a risk of deadlocks) |
A practical rule: a higher isolation level = more protection against concurrency anomalies, but more locks and lower throughput under heavy load. The default ReadCommitted is enough in most business scenarios; Serializable is reserved for financial/critical operations, where even a rare anomaly is unacceptable.
Concurrency Conflicts - optimistic locking (RowVersion)
This is a different mechanism from transaction isolation - it protects against an edit conflict between two independent requests:
public class Order
{
public int Id { get; set; }
public string Status { get; set; }
[Timestamp] // RowVersion - EF Core automatically checks whether the row has changed
public byte[] Version { get; set; }
}
var order = await _context.Orders.FindAsync(1);
order.Status = "Shipped";
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
// SOMEONE ELSE changed this row between the read and the write - your version is stale
Console.WriteLine("The order was changed by someone else, refresh the data");
}
RowVersion generates in SQL the condition WHERE Id = 1 AND Version = @originalVersion on an UPDATE - if in the meantime someone else changed the row (and therefore the Version), the query will find no row to update, and EF Core throws a DbUpdateConcurrencyException.
Summary - when what
| Mechanism | Protects against | When to use |
|---|---|---|
The default SaveChangesAsync() transaction |
A partial write WITHIN a single call | Always, automatically |
An explicit transaction (BeginTransactionAsync) |
A partial write across MULTIPLE SaveChangesAsync() calls |
Multi-step operations requiring atomicity |
| Isolation level | Concurrency anomalies (dirty/non-repeatable read) | Financial/critical operations requiring Serializable |
RowVersion/optimistic concurrency |
Overwriting another user's changes | Editing the same record by many users at once |