Transactions in EF Core
Every SaveChanges call already runs in a transaction. This lesson shows when you need more: several SaveChanges calls that must succeed together, mixing EF Core with raw SQL or ExecuteUpdate, savepoints, and using the retrying execution strategy with transactions.
- StartBeginTransactionAsyncStart one unit of work
- Step 2SaveChangesOrder and lines inserted
- Step 3ExecuteUpdateStock reserved in bulk
- Step 4Raw SQLLogging procedure runs
- EndCommitAsyncAll saved; any error means everything rolls back
SaveChanges is already atomic
When you add an order and its lines and call SaveChangesAsync once, EF Core wraps all the INSERTs in one transaction. Either everything is saved or nothing is. For most actions that is all you need, so prefer one SaveChanges per unit of work.
Explicit transactions
Use BeginTransactionAsync when several SaveChanges calls, ExecuteUpdate or ExecuteDelete calls, or raw SQL commands must succeed or fail together.
await using var tx = await db.Database.BeginTransactionAsync(ct);
var order = new Order { CustomerId = customerId, Lines = lines };
db.Orders.Add(order);
await db.SaveChangesAsync(ct); // order gets its Id
await db.Products
.Where(p => lines.Select(l => l.ProductId).Contains(p.Id))
.ExecuteUpdateAsync(s => s.SetProperty(p => p.ReservedCount, p => p.ReservedCount + 1), ct);
await db.Database.ExecuteSqlAsync($"EXEC dbo.LogOrder {order.Id}", ct);
await tx.CommitAsync(ct); // if anything above throws, disposing tx rolls backSavepoints
A savepoint lets you undo part of a transaction. EF Core creates one automatically before each SaveChanges inside an explicit transaction, and you can add your own.
await using var tx = await db.Database.BeginTransactionAsync();
db.Add(order);
await db.SaveChangesAsync();
await tx.CreateSavepointAsync("BeforeLoyalty");
try
{
db.Add(new LoyaltyPoints { CustomerId = order.CustomerId, Points = 10 });
await db.SaveChangesAsync();
}
catch (DbUpdateException)
{
await tx.RollbackToSavepointAsync("BeforeLoyalty"); // keep the order
}
await tx.CommitAsync();Transactions and retries
- With EnableRetryOnFailure, a manual transaction must run inside the execution strategy so the whole block can be retried: db.Database.CreateExecutionStrategy().ExecuteAsync(async () => { ... }).
- Keep transactions short: never wait on a user, an email server or a payment API while one is open.
- TransactionScope works too, but async code needs TransactionScopeAsyncFlowOption.Enabled.
- Choose the isolation level with BeginTransactionAsync(IsolationLevel.Serializable) only when you need it.
Interview question
Is SaveChanges transactional in EF Core?
Yes. By default SaveChanges and SaveChangesAsync run all pending inserts, updates and deletes in a single transaction, so either all are applied or none are. An explicit transaction is only needed when several SaveChanges calls, ExecuteUpdate or ExecuteDelete calls, or raw SQL commands must be committed together.
Want the full details? Read the official Microsoft documentation for this topic.