Docs / Transactions

Transactions

What this page covers#

This page explains what a transaction is, why it matters, and how MooDb lets you run several database operations as one unit of work.

What is a transaction#

A transaction groups several database operations so they succeed or fail as a whole.

In simple terms:

  • do all of this work together
  • if everything succeeds, save it
  • if something fails, do not keep any part of the work

The simple version#

You begin a transaction, run work through the returned MooTransaction, and call CommitAsync() when everything succeeds.

If the transaction is disposed without being committed, MooDb rolls it back automatically.

</> C#
await using var transaction = await db.BeginTransactionAsync();

try
{
    await transaction.ExecuteAsync(
        "dbo.usp_User_UpdateDisplayName",
        new MooParams()
            .AddInt("@UserId", 1)
            .AddNVarChar("@DisplayName", "Ada Lovelace", 200));

    await transaction.CommitAsync();
}
catch
{
    // No explicit rollback method is needed here.
    // If CommitAsync() is never called, MooDb rolls the transaction back when it is disposed.
    throw;
}

Commit completes the transaction#

This is an important rule.

Once you commit, that MooTransaction instance is complete. It cannot be reused for more execution calls.

That keeps transaction lifecycle errors inside MooDb instead of leaving them to surface later as provider-level SQL transaction failures.

Why this is useful#

Transactions protect your data from being left half-finished.

They also make your code say clearly that several commands belong to one unit of work.

Important notes#

  • BeginTransactionAsync() starts the SQL Server transaction.
  • CommitAsync() saves the work.
  • disposing an uncommitted transaction rolls it back automatically.
  • once committed, that transaction instance is complete and should not be reused.
  • MooTransaction also exposes Sql and Bulk for SQL text and bulk operations inside the same transaction.