Course contentsShow
← C#
Lesson 1080 of 1,90810. Entity Framework Core ModelingFree lesson

Transaction Scope Management

Control atomicity across multiple database operations using explicit transactions.

In this lesson, you will learn how to group multiple database operations into a single atomic unit to ensure your data remains consistent.

The Concept of Atomicity

When working with Entity Framework Core, a standard SaveChanges() call wraps your changes in a transaction automatically. However, there are scenarios where you need to perform multiple distinct operations—such as saving an order, updating inventory, and logging an audit trail—across different method calls or logic blocks. If one of these fails, you don't want the others to persist, leaving your database in a "partially finished" state.

To control this, we use the IDbContextTransaction object. This allows you to define a clear boundary where the database must treat your operations as "all or nothing."

Implementing Explicit Transactions

When you explicitly start a transaction, you take manual control over the Commit and Rollback process. Here is how you can manage this:

using var transaction = await context.Database.BeginTransactionAsync();

try
{
    context.Orders.Add(newOrder);
    await context.SaveChangesAsync();

    context.Inventory.Update(product);
    await context.SaveChangesAsync();

    // If both succeed, commit the changes
    await transaction.CommitAsync();
}
catch (Exception)
{
    // If anything fails, revert everything
    await transaction.RollbackAsync();
    throw;
}

Why Control the Scope?

By using an explicit transaction, you ensure that the database connection stays open and consistent for the duration of the work. If your try block encounters an error, the RollbackAsync() method ensures that any data modified before the crash is discarded, preventing logical corruption.

Note that by using using on the transaction object, the transaction is automatically disposed of if an exception occurs before a commit, acting as a final safety net. This pattern is essential for complex business processes where partial completion is unacceptable.

Key Takeaway: Explicit transactions provide the "all-or-nothing" safety net required to maintain data integrity when your business logic spans multiple dependent database operations.