Coming from Dapper
Open.Database.Extensions is a set of extensions on ADO.NET, not a Dapper clone, and plenty of code uses both. This page is for readers who know Dapper. The biggest difference is not the query syntax: it is who handles the connection. For speed and memory, see Performance. For the size of the code against Dapper, EF Core and plain ADO.NET, see How little code.
Column names that differ from your properties by more than case and underscores need a RowMap<T> declared once: see Renamed columns. Names that differ only by case or underscores need nothing.
The steps, side by side
Each comparison lists the same four steps in the same order, row against row: (1) get the connection, (2) the command or query, (3) the parameters, (4) the terminal and the mapping. A row that one side does not need says "nothing". The SQL is predefined once, so the lines stay short:
public const string ListSql =
"select * from posts where author = @author order by id";
public const string OneSql = "select * from posts where id = @id";
public const string CountSql =
"select count(*) from posts where author = @author";
public const string TouchSql =
"update posts set views = views where author = @author";
public const string InsertSql =
"insert into posts (id, author, title, body, views) "
+ "values (@id, 1, 'Temporary', null, 0)";
Dapper needs no setup. It needs the connection string and the provider type in scope at every call site. It opens a closed connection for the call and closes it again afterwards, so connection.Open() is not required; add it only if you want to control when the connection opens.
Open.Database.Extensions needs a connection factory, created or registered once per application (see Registering the factory once):
var connectionFactory = new DbConnectionFactory<SqliteConnection>(
()
=> new SqliteConnection(connectionString));
After that, no call site writes any connection code. Each count below names the sample it counts (in ConnectionPattern.cs), without the three lines of one-time setup, the // nothing comments and the author and id declarations. Every call of a chain is on its own line, as in the README and Getting started samples.
A list of rows
Dapper
await using var connection = new SqliteConnection(connectionString);
List<Post> posts = (await connection.QueryAsync<Post>(ListSql,
new { author }))
.AsList();
Open.Database.Extensions (factory)
// nothing: the factory creates, opens and disposes the connection
List<Post> posts = await connectionFactory
.Command(ListSql)
.AddParam(author) // name and type inferred from the variable
.Map<Post>()
.ToListAsync(cancellationToken);
Lines you write, counted from dapper_list_call and ode_list_call: Dapper 4, Open.Database.Extensions 5 (plus the one-time setup).
What is different:
- The connection. With Dapper you create it and dispose it, and Dapper opens it if it is closed and closes it when the call finishes. With a factory, the factory creates it for each execution, the command opens it only if it is closed and disposes it when the terminal returns, so it is open only for the duration of the call.
- Rows. Dapper's
QueryAsync<T>reads the whole result into a list and returns a task ofIEnumerable<T>, turned into a list in the sample by Dapper'sAsList(). UnlikeQueryAsync<T>,Map<T>()runs nothing by itself: the query runs when a terminal such asToListAsync()is called.ToListAsync()reads every row into a list during the call.ReadAsync(handler, cancellationToken)offers a lazy sequence that is only valid inside the handler, and it holds the connection while the handler runs: useToListAsync()unless you need to stop early. - Mapping. Both match columns to members by name, ignoring case. Dapper can also bind constructor parameters and fields and, if you turn on
MatchNamesWithUnderscores, matchfirst_nametoFirstName. The extensions set public settable properties (initandrequiredones too) and bind the one public constructor of a record or class (see Positional records), but never set fields. They always ignore underscores when no exact or ignore-case match exists (first_namefeedsFirstName; there is nothing to turn on). A column that differs by more than case and underscores needs aRowMap<T>(see Renamed columns). - NULL. A
NULLinto a nullable member givesnull, and into a non-nullable one throwsValueMappingExceptionnaming the model and the row; a[NullPolicy]on the member or the type, or a[NullValue]on the member, says otherwise (see NULL in a non-nullable column). Like Dapper'sQuerySingle<int>,Map<int>().SingleAsync(cancellationToken)over aNULLthrows. Declareint?when a NULL is expected. - Null parameters. The extensions send a
nullvalue as a database NULL, andAddParam(note)also sends the argument's database type (see Name a parameter from its argument). - Mapping errors. Dapper wraps them in a
DataException("Error parsing column ..."). The extensions throw aValueMappingException(also aDataException) that names the model and the 0-based row; aNullAction.Throwpolicy, or arequiredproperty no column feeds, also names the member and the column.
One row
Dapper
await using var connection = new SqliteConnection(connectionString);
Post? post = await connection.QueryFirstOrDefaultAsync<Post>(OneSql,
new { id });
// nothing: "first or default" and Post are in the method name above
Open.Database.Extensions (factory)
// nothing: the factory creates, opens and disposes the connection
Post? post = await connectionFactory
.Command(OneSql)
.AddParam(id) // name and type inferred from the variable
.Map<Post>()
.FirstOrDefaultAsync(cancellationToken);
Lines you write, counted from dapper_first_call and ode_first_call: Dapper 3, Open.Database.Extensions 5 (plus the one-time setup).
What is different:
- No rows, or several. Dapper's
QueryFirstOrDefaultreturnsdefaultfor no rows and the first row for several.QuerySingleOrDefaultreturnsdefaultfor none and throws for more than one.QueryFirstandQuerySinglethrow when there is no row. The extensions'FirstOrDefaultAsync()returnsnullfor no rows and the first row for several;SingleOrDefaultAsync()returnsnullfor none and throwsInvalidOperationExceptionfor more than one.FirstAsync()throwsInvalidOperationExceptionfor no rows and returns the first row for several;SingleAsync()throws for none and for more than one.
A scalar
Dapper
await using var connection = new SqliteConnection(connectionString);
long count = await connection.ExecuteScalarAsync<long>(CountSql,
new { author });
// nothing: the terminal is the method name above
Open.Database.Extensions (factory)
// nothing: the factory creates, opens and disposes the connection
long count = await connectionFactory
.Command(CountSql)
.AddParam(author) // name and type inferred from the variable
.ExecuteScalarAsync<long>(cancellationToken);
Lines you write, counted from dapper_scalar_call and ode_scalar_call: Dapper 3, Open.Database.Extensions 4 (plus the one-time setup).
What is different:
- The value's type. Dapper converts the provider's value to
Twhere it can (it usesConvert.ChangeType) and returnsdefaultforNULL. The extensions'ExecuteScalarAsync<T>()throwsValueMappingExceptionfor no rows or aNULLinto a non-nullable value type (ask forint?and use??for a default), and converts the value the wayMap<T>()converts a column: an integer into another integer type with a range check (alonginto anint: SQLite returnscount(*)as along, and SQL Server abigintidentity as one), any other value by the general conversion. A value that does not convert, or does not fit, throwsValueMappingException. To convert in your own way, pass a function:ExecuteScalarAsync(value => ...). For many rows of one column,Map<int>().ToListAsync(cancellationToken)converts the same way.
A command with no result set
Dapper
await using var connection = new SqliteConnection(connectionString);
int updated = await connection.ExecuteAsync(TouchSql,
new { author });
// nothing: the terminal is the method name above
Open.Database.Extensions (factory)
// nothing: the factory creates, opens and disposes the connection
int updated = await connectionFactory
.Command(TouchSql)
.AddParam(author) // name and type inferred from the variable
.ExecuteNonQueryAsync(cancellationToken);
Lines you write, counted from dapper_nonquery_call and ode_nonquery_call: Dapper 3, Open.Database.Extensions 4 (plus the one-time setup).
What is different:
- The result. Both return the number of rows affected, as an
int.
A transaction
Dapper opens a closed connection for plain queries and closes it again afterwards. ADO.NET requires an open connection to begin a transaction, so any code that begins one opens the connection first. Dapper does not begin, commit or roll back transactions: its methods take an IDbTransaction that you created from an open connection.
Dapper
await using var connection = new SqliteConnection(connectionString);
await connection.OpenAsync();
await using var transaction = await connection.BeginTransactionAsync();
try
{
await connection.ExecuteAsync(InsertSql, new { id = 100 }, transaction);
await connection.ExecuteAsync(InsertSql, new { id = 101 }, transaction);
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
Open.Database.Extensions (factory)
=> connectionFactory.UsingAsync(connection
// nothing: ExecuteTransactionAsync opens a closed connection
// nothing: ExecuteTransactionAsync begins the transaction
=> connection.ExecuteTransactionAsync(async transaction =>
{
await transaction
.Command(InsertSql)
.AddParam("id", 100)
.ExecuteNonQueryAsync(cancellationToken);
await transaction
.Command(InsertSql)
.AddParam("id", 101)
.ExecuteNonQueryAsync(cancellationToken);
// nothing: it commits when the action returns
}, cancellationToken));
// nothing: it rolls back if the action throws
// nothing: UsingAsync disposes the connection
Lines you write, counted from dapper_transaction_call and ode_transaction_call: Dapper 14, Open.Database.Extensions 12 (plus the one-time setup).
What is different:
- Who opens the connection. Dapper: you, with
Open(), becauseBeginTransaction()needs it. Microsoft'sSqlConnection.BeginTransactionexamples open the connection first, and Microsoft.Data.Sqlite reports that the call "can only be called when the connection is open". The extensions'ExecuteTransactionAsyncopens the connection if it is closed. - Begin, commit, roll back. Dapper: you write all three, usually with a
try/catch, and pass the transaction to every call. The extensions begin the transaction, run your action, commit when it returns without throwing, and roll back (and rethrow) when it throws.ExecuteTransactionConditionalAsynccommits only when your action returnstrue; otherwise it rolls back. - A connection that was already open. The extensions close only a connection they opened; an open connection stays open.
- Where the helpers live. They are extension methods on
DbConnection(ExecuteTransactionAsync,ExecuteTransactionConditionalAsync), with an optional isolation level and a cancellation token. With a factory, call them insidefactory.UsingAsync(connection => ...)(see foundation).
A connection you own
If you would rather own the connection, the extensions work on a connection the way Dapper does:
Dapper
await using var connection = new SqliteConnection(connectionString);
List<Post> posts = (await connection.QueryAsync<Post>(ListSql,
new { author }))
.AsList();
Open.Database.Extensions (your connection)
await using var connection = new SqliteConnection(connectionString);
List<Post> posts = await connection
.Command(ListSql)
.AddParam(author) // name and type inferred from the variable
.Map<Post>()
.ToListAsync(cancellationToken);
Lines you write, counted from dapper_list_call and ode_list_own: Dapper 4, Open.Database.Extensions 6.
What is different:
- Nothing about the connection. You create it and dispose it in both. Each opens a closed connection for the call and closes only what it opened; neither needs
Open(). The extensions never dispose a connection you gave them. - Concurrency. A command built from one connection throws
InvalidOperationExceptionif two terminals run at once.
The total
Across the list, one row, scalar and no-result-set calls above, Dapper takes 13 lines and the extensions 18, plus three lines of one-time setup.
Who owns what
| Dapper | Extensions with a factory | Extensions with your connection | |
|---|---|---|---|
| Creates the connection | You, at each call site | The factory, for each execution | You |
| Needs the connection string and provider type in scope | At each call site | Once, where the factory is created | You, where you create it |
| Opens it | Dapper, if it is closed | The command, if it is closed | The command, only if it is closed |
| Closes it | Dapper, if it opened it | The command disposes it | The command, only if it opened it |
| Disposes it | You | The command | You. Never the command |
Registering the factory once
IDbConnectionFactory<TConnection> is the abstraction, DbConnectionFactory<TConnection> wraps any Func<TConnection>, and SqlConnectionFactory (in the MSSqlClient package) takes a connection string. The library has no dependency-injection extension of its own: register the factory with whatever container you use. With Microsoft.Extensions.DependencyInjection:
var services = new ServiceCollection();
// A singleton is fine: the factory holds no connection,
// it only creates them.
services.AddSingleton<IDbConnectionFactory<SqliteConnection>>(
new DbConnectionFactory<SqliteConnection>(
static ()
=> new SqliteConnection(Db.ConnectionString)));
services.AddTransient<PostService>();
await using ServiceProvider provider = services.BuildServiceProvider();
var service = provider.GetRequiredService<PostService>();
Consumers take the factory as a constructor parameter and never see a connection string:
public class PostService(
IDbConnectionFactory<SqliteConnection> connectionFactory)
{
public ValueTask<List<Post>> ByAuthorAsync(
int author,
CancellationToken cancellationToken)
=> connectionFactory
.Command(ListSql)
.AddParam(author) // name and type inferred from the variable
.Map<Post>()
.ToListAsync(cancellationToken);
}
For SQL Server, register SqlConnectionFactory as IDbConnectionFactory<SqlConnection>:
services.AddSingleton<IDbConnectionFactory<SqlConnection>>(
new SqlConnectionFactory(connectionString));
A singleton is fine because the factory holds no connection: its Create() method returns a new connection object each time.
Renamed columns
Dapper can match underscored names (MatchNamesWithUnderscores) or you can alias the columns in SQL. For a column that differs by more than case and underscores, declare a RowMap<T> once (see Columns named differently):
public static RowMap<Person> PersonMap
=> field ??= [
new(nameof(Person.Id), "person_id"),
new(nameof(Person.FirstName), "first_name"),
new(nameof(Person.LastName), "last_name"),
];
and pass it to Map<T>:
// PersonMaps.PersonMap is the RowMap<Person>
// declared once in the map_declared sample (Mapping.cs).
Person[] people = await connection
.Command("""
select person_id, first_name, last_name
from people
order by person_id
""")
.Map<Person>(PersonMaps.PersonMap)
.ToArrayAsync(cancellationToken);
Positional records
A positional record works with both: Dapper binds its constructor, and so does Map<T>(). Both read this record:
public record PostRecord(long Id, long Author, string Title, string? Body);
Dapper
// Dapper binds constructor parameters, so a positional record works.
List<PostRecord> posts = (await connection
.QueryAsync<PostRecord>(
"select id, author, title, body from posts order by id"))
.AsList();
Open.Database.Extensions
// Map<T>() binds the one public constructor, so the same record works.
List<PostRecord> posts = await connection
.Command("select id, author, title, body from posts order by id")
.Map<PostRecord>()
.ToListAsync(cancellationToken);
What is different:
- Choosing the constructor. Dapper picks a constructor by the columns of the query. The extensions use the one public constructor, or the public parameterless one when the type has it, whatever the columns. A type with two or more public constructors and none without parameters throws
InvalidOperationExceptionat the call: make all but one non-public, or write aMap(selector). - A parameter with no column, and NULL. A parameter no column feeds takes its declared default value, else
default. ANULLinto a non-nullable parameter throws, unless[NullPolicy(NullAction.Default)]gives it the declared default too (see A missing column and a NULL). requiredandinit. The extensions setinitproperties after the constructor and enforcerequiredones: a result with no column for arequiredproperty throwsValueMappingExceptionat its first row (seerequiredandinitmembers).
Async and cancellation
Dapper's QueryAsync<T> returns a Task<IEnumerable<T>>, and a cancellation token travels in a CommandDefinition. The extensions' terminals have Async twins that take a CancellationToken and return a ValueTask, for example ToArrayAsync(cancellationToken); a token set on the command with UseCancellationToken(token) is combined with it, and either one cancels the call. The same holds for ExecuteNonQueryAsync, ExecuteScalarAsync and ExecuteReaderAsync. Await a ValueTask once, as usual; to pass it to Task.WhenAll, call .AsTask() first.
Where Dapper does more
Dapper has features this library does not offer:
- Choosing a constructor by the columns. The extensions use the one public constructor, whatever the columns (see Positional records).
- Multi-mapping and
QueryMultiple. Dapper maps several types from one row and reads several result sets from one call. - Type handlers and custom type maps.
SqlMapper.AddTypeHandlerandSqlMapper.SetTypeMap. - Dynamic results.
Query(sql)without a type returns dynamic rows. - Batch execution.
Execute(sql, IEnumerable<parameters>)runs one command once for every item. The extensions have no equivalent: loop over the items and run the command for each, inside oneExecuteTransactionAsync(see A transaction). - Parameter bags and output parameters. An anonymous object,
new { id = 1 }, becomesAddParams(new { id = 1 })(see Name a parameter from its argument).DynamicParametershas no equivalent: add each value withAddParam. Output parameters can be sent, but their values cannot be read back, so a procedure that returns values through them needs Dapper or plain ADO.NET. The return value is readable:ExecuteReturnAsync<T>()(see Return values and output parameters).
With the extensions, use Map(selector) or ExecuteReader(reader => ...) for those jobs. For dynamic rows, AsObjectArrays() gives each row as an object?[] (AsDictionaryRows() as a dictionary): see Rows without a model.
Which method becomes which terminal
The terminals are async and need a factory of a DbConnection type: IDbConnectionFactory<DbConnection> (any factory of a DbConnection type converts to it) or SqlConnectionFactory; the non-generic IDbConnectionFactory has no Async terminals.
| Dapper | Open.Database.Extensions, after Command(sql) and AddParam(...) |
|---|---|
Query<T>, QueryAsync<T> |
Map<T>().ToListAsync(cancellationToken) (or ToArrayAsync(cancellationToken)), which returns a ValueTask |
QueryFirstOrDefault<T>, QuerySingleOrDefault<T> |
Map<T>().FirstOrDefaultAsync(cancellationToken), Map<T>().SingleOrDefaultAsync(cancellationToken) |
QueryFirst<T>, QuerySingle<T> |
Map<T>().FirstAsync(cancellationToken), Map<T>().SingleAsync(cancellationToken) |
Query<int> over one column |
Map<int>().ToListAsync(cancellationToken): the first column, converted like a property (a long into int is range-checked); a NULL throws, so declare int? when a NULL is expected. |
ExecuteScalar<T> |
ExecuteScalarAsync<T>(cancellationToken); it converts the value to T as Map<T>() does |
Execute |
ExecuteNonQueryAsync(cancellationToken) |
Execute("usp_x", ..., commandType: CommandType.StoredProcedure) |
StoredProcedure("usp_x"), then AddParam(...) and ExecuteNonQueryAsync(cancellationToken) (see Return values and output parameters) |
| A transaction passed to each call | Start from the transaction: transaction.Command(sql) |