EF Core Transaction Scope — Complete Guide
In this tutorial, you'll learn about EF Core Transaction Scope. We cover key concepts, practical examples, and best practices.
You create an order, deduct inventory, and charge the customer. If the charge fails, the order should not be created and inventory should not be deducted. Without a transaction, partial failures leave your data inconsistent.
Wrong
public async Task CreateOrder(Order order)
{
db.Orders.Add(order);
await db.SaveChangesAsync();
await DeductInventoryAsync(order);
await ChargeCustomerAsync(order);
// If ChargeCustomerAsync throws, order exists but inventory deducted
}
Output: If ChargeCustomerAsync fails, the order is saved but inventory is deducted and the customer was not charged. Inconsistent state.
Right
public async Task CreateOrder(Order order)
{
using var transaction = await db.Database.BeginTransactionAsync();
try
{
db.Orders.Add(order);
await db.SaveChangesAsync();
await DeductInventoryAsync(order);
await ChargeCustomerAsync(order);
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
Output: All operations succeed together or fail together. The transaction is atomic.
Multiple SaveChanges in one transaction:
using var tx = await db.Database.BeginTransactionAsync();
db.Orders.Add(order);
await db.SaveChangesAsync();
db.OrderItems.AddRange(order.Items);
await db.SaveChangesAsync();
await tx.CommitAsync();
Prevention
- Use
BeginTransactionAsyncfor operations spanning multipleSaveChangescalls. - Use
CommitAsyncto make changes permanent. - Use
RollbackAsyncin catch blocks to undo changes on failure. - Use
usingorfinallyto ensure rollback if commit is not called. - Use
Database.CurrentTransactionto check if a transaction is active. - Use transaction scopes (
TransactionScope) for distributed transactions across databases. - Keep transactions as short as possible to reduce lock contention.
Common Mistakes with core transaction scope
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Transactions are critical in DodaTech's order processing pipeline. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro