Handling Database Transactions with SQLKata in C#


When a use case makes several database changes, those changes often represent one logical operation. If one step succeeds and a later step fails, the database can be left in a partial state. A transaction groups the operations so they either commit together or roll back together.

When to use a transaction

This kind of explicit transaction handling is not needed for one database operation. A single SQL statement is already atomic in most relational databases, so a standalone insert, update, delete, or read normally needs no transaction started and managed by application code.

Use an explicit transaction when a use case performs multiple related database operations that must succeed or fail together. These can be reads, writes, and deletes. For example, creating an order, adding its line items, and updating inventory may need to be treated as one unit: if any step fails, the others should not leave partial changes behind. Keep the transaction focused and short, then commit after all required operations succeed.

Open a transaction on the query connection

SQLKata executes queries through a QueryFactory, which is configured with a database connection and compiler. Start the transaction on the same connection used by the QueryFactory. This is essential: a transaction belongs to one connection, and commands using another connection will not be part of it.

With Npgsql and PostgreSQL, NpgsqlTransactionFactory implements ITransactionFactory to open the connection and start a transaction. The interface keeps the application code independent of the database provider:

using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;

public interface ITransactionFactory
{
    Task<DbTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default);
}

The PostgreSQL implementation uses the same connection configured for SQLKata’s QueryFactory:

using System.Threading;
using System.Threading.Tasks;

using Npgsql;

public sealed class NpgsqlTransactionFactory(NpgsqlConnection connection) : ITransactionFactory
{
    public async Task<DbTransaction> BeginTransactionAsync(
        CancellationToken cancellationToken = default)
    {
        await connection.OpenAsync(cancellationToken);
        return await connection.BeginTransactionAsync(cancellationToken);
    }
}

The factory centralizes transaction creation so application code can begin a transaction without depending directly on Npgsql. Dependency injection should ensure that the factory and QueryFactory use the same scoped connection for the unit of work.

Pass the transaction to SQLKata

Every SQLKata execution that belongs to the unit of work must receive the transaction. A repository method can accept IDbTransaction and forward it to the execution method:

using System.Data;
using System.Threading;
using System.Threading.Tasks;

using SqlKata.Execution;

public Task<int> UpdateStatus(
    int id,
    string status,
    IDbTransaction transaction,
    CancellationToken cancellationToken)
{
    return db.Query("items")
        .Where("id", id)
        .UpdateAsync(
            new { status },
            transaction: transaction,
            cancellationToken: cancellationToken);
}

Use the same transaction for every participating query. Keep values in SQLKata’s query API so they are parameterized, and avoid opening a separate connection inside a repository.

Coordinate the unit of work

The application operation that knows which database changes belong together should define the transaction boundary. It starts the transaction, passes it to the data access methods, and commits after all required work succeeds:

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public static async Task<int> CreateOrder(
    ITransactionFactory transactionFactory,
    OrderRepository repository,
    IReadOnlyList<OrderLine> lines,
    CancellationToken cancellationToken)
{
    await using var transaction = await transactionFactory.BeginTransactionAsync(cancellationToken);

    try
    {
        var orderId = await repository.InsertOrder(transaction, cancellationToken);
        await repository.InsertOrderLines(orderId, lines, transaction, cancellationToken);

        await transaction.CommitAsync(cancellationToken);

        return orderId;
    }
    catch (Exception exception)
    {
        // Log the error here.
        // ...

        // Omit the token or pass CancellationToken.None so a canceled request does not cancel rollback.
        // Do NOT pass cancellationToken here
        await transaction.RollbackAsync();

        throw;
    }
}

await using disposes the transaction even if an operation throws before commit. Disposing an uncommitted transaction rolls it back. If the operation handles a business failure and returns a normal result, explicitly roll back before returning. Pass CancellationToken.None, or omit the argument, so rollback can continue even if the request token was canceled. The default token is non-cancelable; passing the request token could stop rollback and leave cleanup to transaction disposal. If rollback itself throws while handling another exception, log the rollback failure separately so it does not hide the original error.

Commit only after every operation that must be atomic has succeeded. Once the transaction commits, a later failure cannot undo those changes.

Good practices

Summary

Use a transaction to group the database operations in one logical unit of work. Start it on the same connection SQLKata uses, pass it to each participating query, and commit only after all required work succeeds. This gives multi-step operations a clear, reliable all-or-nothing outcome.

Daniel Opitz

Daniel Opitz

Developer, Trainer & Open Source Contributor. Passionate about PHP, Slim Framework, and clean code.

Comments

↑ Back to Blog