The foundation
Most of the library is a provider-agnostic set of extension methods on the standard ADO.NET types (IDbConnection, DbConnection, IDbCommand, IDataReader, IDbTransaction).
Connection factories
A connection factory creates connections without the caller knowing a connection string:
IDbConnectionFactoryandIDbConnectionFactory<TConnection>are the abstractions, which fit dependency injection. TheAsyncterminals need aDbConnection, so a service that awaits should depend onIDbConnectionFactory<DbConnection>(or a factory of a specificDbConnectiontype); commands from the non-genericIDbConnectionFactoryhave noAsynctwins. ADbQuerytakes only factories and pools ofDbConnections (the compiler rejects another type); a source that supplies something else at run time fails the run withInvalidOperationException, after the connection it supplied is disposed (factory) or given back (pool).DbConnectionFactory<TConnection>wraps anyFunc<TConnection>.SqlConnectionFactory(in theMSSqlClientpackage) wraps a connection string for SQL Server.
// A connection factory: each command built from it opens its own
// connection and disposes it afterwards.
public static IDbConnectionFactory<SqliteConnection> Factory
=> field ??= new DbConnectionFactory<SqliteConnection>(
static ()
=> new SqliteConnection(ConnectionString));
Helpers on a factory: Using creates a connection, runs your action, and disposes the connection (it does not open it). Open does the same after making sure the connection is open. Command and StoredProcedure start an expressive command.
Who owns the connection
| You start from | The connection is... | When a terminal runs |
|---|---|---|
A connection factory (factory.Command(sql)) |
Created by the command | Created, opened if needed, then disposed |
A connection (connection.Command(sql)) |
Yours | Opened only if it was closed, then closed again only if the command opened it. Never disposed |
factory.Using(connection => ...) |
Created by Using |
Disposed when your action returns. Not opened for you |
// A closed connection is opened for the call
// and closed again afterwards.
await connection.CloseAsync();
ConnectionState closedBefore = connection.State;
await connection
.Command("select 1")
.ExecuteScalarAsync(cancellationToken);
ConnectionState closedAfter = connection.State;
// A connection that was already open stays open.
await connection.OpenAsync(cancellationToken);
ConnectionState openBefore = connection.State;
await connection
.Command("select 1")
.ExecuteScalarAsync(cancellationToken);
ConnectionState openAfter = connection.State;
A command built from a single connection refuses concurrent terminals: a second call while one is running throws InvalidOperationException.
Open late, close early
Several helpers exist to keep the time a connection is open short:
EnsureOpen()andEnsureOpenAsync()open a closed (or broken) connection and return its prior state, so you can restore it.- Rows are read with
Map<T>()and a terminal (Mapping rows to objects); a buffered terminal such asToListAsyncreleases the connection as soon as it returns.
Transactions
ExecuteTransactionConditionalAsync begins a transaction, runs your action, and commits only if the action returns true, nothing throws and the cancellation token was not cancelled. Otherwise it rolls back. A connection that was closed is opened for the transaction and closed again afterwards; one that was open stays open.
// The factory creates the connection;
// ExecuteTransactionConditionalAsync opens it if it is closed
// and starts the transaction.
// Returning true commits; false (or a throw) rolls back.
// Here the caller decides: shouldCommit is a bool passed in.
bool committed = await connectionFactory.UsingAsync(connection
=> connection.ExecuteTransactionConditionalAsync(
async transaction =>
{
await transaction
.Command("""
insert into posts (id, author, title, body, views)
values (100, 1, 'Temporary', null, 0)
""")
.ExecuteNonQueryAsync(cancellationToken);
return shouldCommit;
},
cancellationToken));
ExecuteTransactionAsync is the same without the condition: it commits unless the action throws. The token is checked once more after your action returns: a token cancelled by then throws OperationCanceledException and nothing commits. The commit itself is sent without the token, so cancelling while it runs does not interrupt it.
// The token is checked after the action returns:
// a token cancelled by then never commits.
// The commit itself is sent without the token.
await connectionFactory.UsingAsync(connection
=> connection.ExecuteTransactionAsync(async transaction =>
{
await transaction
.Command("""
insert into posts (id, author, title, body, views)
values (100, 1, 'Temporary', null, 0)
""")
.ExecuteNonQueryAsync(cancellationToken);
}, cancellationToken));
Reader and command helpers
The foundation also includes helpers you can use without the expressive syntax: ForEach and ForEachAsync over a reader, Select and SelectAsync, AsAsyncEnumerable, ToDataTable and friends on commands. Buffered reads copy the rows out of the reader first, so the connection can be released early. For rows without a model use AsObjectArrays() or AsDictionaryRows() (see Rows without a model); for typed rows Map<T>() is the better route (see Performance).
The reader helpers that take a token (ForEach, ForEachAsync, IterateWhile, Select, SelectAsync) check it at the top of the loop, before each read (the async forms hand it to ReadAsync, so the provider cancels the read itself). A cancel throws OperationCanceledException and the read is not made; the rows already handed out stay handed out. A cancel while the last row is handled throws at the next check. Once a read has returned no row the result is complete, and a cancel after that is not an error. To stop early, return false from the predicate or break out of the loop: do not cancel. AsAsyncEnumerable is the exception to the throwing rule: a cancelled token ends its enumeration quietly, and the rows already yielded stay yielded.
// The token is checked before each read.
// The token goes to ReadAsync; a cancel throws
// OperationCanceledException and the read is not made.
// The rows already handed out stay handed out.
// Once a read has returned no row, a cancel is not an error.
// To stop early without an exception, break out of the loop.
using var cts = new CancellationTokenSource();
await using SqliteCommand command = connection.CreateCommand();
command.CommandText = "select id from posts order by id";
await using SqliteDataReader reader = await command.ExecuteReaderAsync();
try
{
await foreach (int id in reader.SelectAsync(
static record => record.GetInt32(0),
cts.Token))
{
seen.Add(id);
if (id == 2) cts.Cancel();
}
}
catch (OperationCanceledException)
{
canceled = true;
}
See the API reference for the full list.