Transactions and connection lifetime
On this page
Verify rollback and commit
Use UseTranAsync on one OrmClient when two writes must succeed together. Install both packages from quick start, then replace Program.cs with this complete example. The first transaction deliberately throws after one insert; the second writes both records successfully.
using System.Data;
using TORM;
await using var db = new OrmClient(new ConnectionConfig
{
DatabaseType = DatabaseType.Sqlite,
ConnectionString = "Data Source=:memory:"
});
await db.CodeFirst!.InitTableAsync<Device>();
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var token = cancellation.Token;
try
{
await db.UseTranAsync(async () =>
{
await db.Insertable(new Device { Id = 1, Code = "P-101" }).ExecuteAsync(token);
throw new InvalidOperationException("Demonstration failure.");
}, cancellationToken: token, isolationLevel: IsolationLevel.Serializable);
}
catch (InvalidOperationException ex) when (ex.Message == "Demonstration failure.")
{
Console.WriteLine("Failed transaction rolled back.");
}
Console.WriteLine($"After rollback: {await db.Queryable<Device>().CountAsync(token)}");
await db.UseTranAsync(async () =>
{
await db.Insertable(new Device { Id = 1, Code = "P-101" }).ExecuteAsync(token);
await db.Insertable(new Device { Id = 2, Code = "P-102" }).ExecuteAsync(token);
}, cancellationToken: token, isolationLevel: IsolationLevel.Serializable);
Console.WriteLine($"After commit: {await db.Queryable<Device>().CountAsync(token)}");
/// <summary>事务示例中需要成组写入的设备。</summary>
[OrmTable("transaction_devices")]
public sealed class Device
{
/// <summary>显式主键用于验证回滚后可再次写入同一身份。</summary>
[OrmColumn(IsPrimaryKey = true)]
public long Id { get; set; }
/// <summary>事务内写入的业务编码。</summary>
[OrmColumn(Length = 64, IsNullable = NullableState.Nullable)]
public string Code { get; set; } = "";
}Run dotnet run. Expected output:
Failed transaction rolled back.
After rollback: 0
After commit: 2Rollback removes the first insert too, allowing the next transaction to insert Id = 1 again. The in-memory database is released when the program exits.
Batching does not define commit boundaries
InsertableRange batches control input or provider write costs. When the business requires all-or-nothing behavior, keep every batch inside one outer transaction. Insert this fragment before the example’s Device declaration. It adds four rows sequentially after the first two committed rows:
var pending = Enumerable.Range(3, 4)
.Select(id => new Device { Id = id, Code = $"P-{id + 100}" });
await db.UseTranAsync(async () =>
{
foreach (var batch in pending.Chunk(2))
await db.InsertableRange(batch).ExecuteAsync(token);
}, cancellationToken: token);
Console.WriteLine($"After batches: {await db.Queryable<Device>().CountAsync(token)}");Additional output:
After batches: 6| Approach | Atomicity and cost |
|---|---|
Sequential InsertableRange calls inside one UseTranAsync | One connection and business commit boundary; later failure can roll back earlier batches |
A separate UseTranAsync for each batch | Earlier commits survive later failures; use when the business explicitly permits partial success |
| Provider-owned transactions without an outer transaction | Scope depends on the provider and operation; it does not replace a transaction spanning multiple calls |
Task.WhenAll on the same client | Shares mutable connection and transaction state; do not use it to accelerate this pattern |
SQLite range insert manages its own transaction when needed and no transaction exists. It joins an existing outer transaction without committing it. Other providers define their own transaction scope. BatchSize does not guarantee one database command per batch.
Batch projection bounds current entity-array allocations, while the outer transaction can still hold locks and grow its log. Parse files and run database-independent validation before the transaction; perform final fact checks and writes inside it. The XLSX validation and transaction example demonstrates rollback on a later batch conflict.
Exceptions and cancellation
UseTranAsync begins the transaction, executes the callback and commits. On failure or cancellation it attempts rollback with CancellationToken.None, then rethrows the original exception. Failure to begin does not execute the callback or silently lower isolation.
The outer token controls transaction begin and commit; it is not injected into callback operations. Pass token explicitly to each ExecuteAsync.
UseTranAsync<T> returns a result. Swallowing an exception inside the callback may allow the outer transaction to commit.
Database rollback does not undo messages, remote API calls or file writes.
Manual transactions
Ado.BeginTransactionAsync, CommitTransactionAsync and RollbackTransactionAsync expose explicit control. The caller owns error paths, cancellation cleanup and disposal. Avoid nested automatic transaction wrappers inside an active transaction.
Transactions belong to one client connection. Other clients selected with GetConnection do not automatically participate in a distributed transaction.
Concurrency
AdoProvider retains one DbConnection and is not thread-safe. Do not share one OrmClient concurrently across requests or tasks.
await using var independent = db.CopyNew();CopyNew() preserves configured database routes; CopyCurrentConnection() copies only the current connection and related configuration. The caller owns the new client. Active transactions are not inherited. Query builders also contain mutable state and must not be shared across requests.
A copy can access the same file or server database. With SQLite Data Source=:memory:, a new connection gets a separate in-memory database; this example’s tables and records are not copied.
Readers and completion callbacks
Keep clients alive until async enumeration ends. Dispose raw ExecuteReaderAsync readers explicitly. The database driver manages connection pooling.
EnlistTransactionCompletion and its async counterpart register completion participants. TransactionOutcome distinguishes Committed and OutcomeKnown; OnTransactionCompletionError reports cleanup failures. Unknown outcomes require reconciliation before retrying external side effects.