IC Improve Code Recipes

Recipe 1.5 · C#

Transactions That Commit or Roll Back

Problem

An order header and its lines must be saved together. Without a transaction, a failure after the header insert leaves an order with no lines. With a carelessly written transaction, a failure leaves the transaction open, holding locks, until the connection is reset.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: the second command is not enlisted,
// and nothing rolls back on failure.
conn.Open();
SqlTransaction tx = conn.BeginTransaction();
SqlCommand header = new SqlCommand(insertHeader, conn, tx);
int orderId = Convert.ToInt32(header.ExecuteScalar());
foreach (var line in lines)
{
    SqlCommand cmd = new SqlCommand(insertLine, conn);
    // ... add parameters, ExecuteNonQuery()
}
tx.Commit();
conn.Close();

The line command is missing its transaction argument, so SQL Server throws an error saying the command must have a transaction when the connection has a pending one. When that exception escapes, nothing rolls back, and nothing closes the connection.

The improved recipe

C#
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;

namespace ImproveCode.Data;

public sealed record NewOrderLine(
    int ProductId, int Quantity, decimal UnitPrice);

public sealed class OrderWriter(IDbConnectionFactory db)
{
    private const string InsertHeaderSql = """
        INSERT INTO dbo.SalesOrder (CustomerId, OrderedUtc)
        OUTPUT INSERTED.OrderId
        VALUES (@CustomerId, SYSUTCDATETIME());
        """;

    private const string InsertLineSql = """
        INSERT INTO dbo.SalesOrderLine
            (OrderId, ProductId, Quantity, UnitPrice)
        VALUES (@OrderId, @ProductId, @Quantity, @UnitPrice);
        """;

    public async Task<int> CreateAsync(
        int customerId,
        IReadOnlyList<NewOrderLine> lines,
        CancellationToken ct = default)
    {
        await using var connection = await db.OpenAsync(ct);
        await using var tx = (SqlTransaction)
            await connection.BeginTransactionAsync(ct);
        try
        {
            int orderId;
            await using (var header = new SqlCommand(
                InsertHeaderSql, connection, tx))
            {
                header.Parameters.AddInt("@CustomerId", customerId);
                orderId = (int)(await header.ExecuteScalarAsync(ct))!;
            }

            foreach (NewOrderLine line in lines)
            {
                await using var command = new SqlCommand(
                    InsertLineSql, connection, tx);
                command.Parameters.AddInt("@OrderId", orderId);
                command.Parameters.AddInt("@ProductId", line.ProductId);
                command.Parameters.AddInt("@Quantity", line.Quantity);
                command.Parameters.AddDecimal(
                    "@UnitPrice", 19, 4, line.UnitPrice);
                await command.ExecuteNonQueryAsync(ct);
            }

            await tx.CommitAsync(ct);
            return orderId;
        }
        catch
        {
            await tx.RollbackAsync(CancellationToken.None);
            throw;
        }
    }
}

How it works

One connection, one transaction, and every command created with both. The try block ends in CommitAsync. Any exception before that point lands in the catch, which rolls back and rethrows the original exception with throw; so the stack trace survives. The rollback deliberately ignores the caller's cancellation token: if the request was cancelled, you still want the rollback to finish.

await using on the transaction is a second safety net. Disposing a transaction that was neither committed nor rolled back rolls it back. OUTPUT INSERTED.OrderId returns the new identity value in the same statement, which avoids the classic @@IDENTITY bug where a trigger's insert returns the wrong ID.

Variations and pitfalls

  • Many lines? A loop of inserts is fine for an order with ten lines. For hundreds, pass the lines as a table-valued parameter (Recipe 1.6) and insert them in one statement.
  • Keep transactions short. Do not call a web service, send e-mail or wait for user input while a transaction is open. Locks are held until commit.
  • TransactionScope. It works with Microsoft.Data.SqlClient, but with async code you must create it as new TransactionScope(TransactionScopeAsyncFlowOption.Enabled), or the ambient transaction will not flow across await. Opening a second connection inside the scope can promote it to a distributed transaction, which needs MSDTC on .NET Framework and is only partly supported on modern .NET. I use explicit SqlTransaction unless I truly need to span several connections.
  • Transactions in procedures. If the whole unit of work is in one stored procedure, keep the transaction in the procedure and use SET XACT_ABORT ON. Chapter 2 has the template.