Transactions allow you to execute a group of queries atomically, meaning either all changes are applied or none are. This is essential for maintaining data consistency when performing related operations that must not be partially applied.
Method | Description |
|---|---|
session.BeginTransaction() | Create a new transaction scoped to the current session. |
txn.Commit() | Commit the transaction to the database, applying all changes made within |
txn.Cancel() | Cancel and discard all changes made in the transaction. |
.BeginTransaction()
Creates a new transaction scoped to the current session. Transactions allow you to execute multiple queries atomically.
await session.BeginTransaction(cancellationToken)Arguments
Arguments | Description |
|---|---|
cancellationToken | The cancellationToken enables graceful cancellation of asynchronous |
Example usage
// Begin a new transaction on the current session
await using var txn = await db.BeginTransaction();
// Execute queries within the transaction
await txn.Create("person", new { Name = "John" });
await txn.Create("person", new { Name = "Jane" });
// Commit all changes atomically
await txn.Commit(); .Commit()
Commits the transaction to the database, applying all changes made within the transaction scope.
After committing, the transaction cannot be used again.
await txn.Commit(cancellationToken)Arguments
Arguments | Description |
|---|---|
cancellationToken | The cancellationToken enables graceful cancellation of asynchronous |
Example usage
await using var txn = await db.BeginTransaction();
await txn.Create("order", new { Total = 99.99 });
await txn.Create("invoice", new { OrderId = "order:1" });
// Commit all changes — either both succeed or neither does
await txn.Commit(); .Cancel()
Cancels and discards all changes made in the transaction.
After canceling, the transaction cannot be used again.
await txn.Cancel(cancellationToken)Arguments
Arguments | Description |
|---|---|
cancellationToken | The cancellationToken enables graceful cancellation of asynchronous |
Example usage
await using var txn = await db.BeginTransaction();
try
{
await txn.Create("order", new { Total = 99.99 });
// ... more operations
await txn.Commit();
}
catch
{
// Discard all changes on error
await txn.Cancel();
}