Skip to content

EF Core Transaction Scope — Complete Guide

DodaTech Updated 2026-06-24 2 min read

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.

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 BeginTransactionAsync for operations spanning multiple SaveChanges calls.
  • Use CommitAsync to make changes permanent.
  • Use RollbackAsync in catch blocks to undo changes on failure.
  • Use using or finally to ensure rollback if commit is not called.
  • Use Database.CurrentTransaction to 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

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. 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

Does SaveChanges wrap in a transaction by default?

Yes. A single SaveChanges call wraps all its operations in a database transaction. Multiple SaveChanges calls are NOT wrapped — each is its own transaction. Use BeginTransactionAsync to group multiple SaveChanges calls.

Can I use transactions across multiple DbContexts?

For the same database, share the same connection or use TransactionScope. For different databases, use distributed transactions (MSDTC) or the outbox pattern. Distributed transactions have performance overhead.

What is the isolation level of EF Core transactions?

The default is the database provider default (usually READ COMMITTED). You can specify isolation: BeginTransactionAsync(IsolationLevel.Serializable). Higher isolation levels increase data consistency but reduce concurrency.

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