Define a transaction explicitly
WithTransactionAsync starts the transaction, commits after success, and rolls back
when the action throws. Every command on the connection participates in it.
An explicit unit of work
Transaction.cs
await using var fusionConnection = await context.OpenFusionConnectionAsync();
return await fusionConnection.WithTransactionAsync(async cancellationToken =>
{
await fusionConnection.ExecuteAsync(
"""
UPDATE Department
SET Budget = Budget + @increase
WHERE DepartmentID = @departmentId;
""",
new Parameters
{
{ "increase", 10_000m },
{ "departmentId", 2 }
},
cancellationToken);
return await fusionConnection.GetValueAsync<decimal>(
"SELECT Budget FROM Department WHERE DepartmentID = @departmentId;",
new Parameters { { "departmentId", 2 } },
cancellationToken);
}, context.CancellationToken);