DbTransact

Classes > DataProvider > DbTransact

Provides transactional helpers as extension methods for ``. Opens a transaction, executes the provided delegate, and commits or rolls back accordingly.

public static class DbTransact

Example

// Execute multiple operations in a transaction
await connection.Transact(async tx =>
{
    await tx.InsertUserAsync(new User { Id = Guid.NewGuid(), Name = "John" });
    await tx.InsertOrderAsync(new Order { UserId = userId, Total = 99.99m });
});

// Execute with a return value
var userId = await connection.Transact(async tx =>
{
    var user = new User { Id = Guid.NewGuid(), Name = "Jane" };
    await tx.InsertUserAsync(user);
    return user.Id;
});

Methods

Transact(DbConnection, Func<IDbTransaction, Task>)

public static Task Transact(this DbConnection cn, Func<IDbTransaction, Task> body)

Executes the specified asynchronous body within a database transaction. The transaction is committed on success, or rolled back if an exception is thrown.

Parameters:

Name Type Description
cn DbConnection The database connection. It will be opened if not already open.
body Task> The asynchronous delegate to execute within the transaction.

Returns: Task - A task that completes when the transactional operation finishes.

Transact<T>(DbConnection, Func<IDbTransaction, Task<T>>)

public static Task<T> Transact<T>(this DbConnection cn, Func<IDbTransaction, Task<T>> body)

Executes the specified asynchronous body within a database transaction and returns a result. The transaction is committed on success, or rolled back if an exception is thrown.

Parameters:

Name Type Description
cn DbConnection The database connection. It will be opened if not already open.
body Task<<T>>> The asynchronous delegate to execute within the transaction.

Returns: Task<<T>> - A task that resolves to the result returned by body.