Useful set of utilities and abstractions for simplifying modern database operations and ensuring dependency injection compatibility.
- Minimize connection open time.
- Deferred/lazy transformation.
- Optimize for specific use cases.
- Minimize boilerplate code.
- Provides a fluent interface for database operations.
- Supports dependency injection for connection factories.
- Support both synchronous and asynchronous operations.
- Provides expressive commands for executing SQL queries and stored procedures.
Connection factories facilitate creation and disposal of connections without the concern of a connection reference or need for awareness of a connection string.
A SqlConnectionFactory is provided and can be overridden to provide more specific dependency injection configurations.
The provided expressive command classes allow for an expressive means to append parameters and execute the results without lengthy complicated setup.
Extensions are provided to create commands from connection factories.
var result = connectionFactory
.StoredProcedure("[procedure name]")
.AddParam("a",1)
.AddParam("b",true)
.AddParam("c","hello")
.ExecuteScalar();Instead of writing this:
var myResult = new List<T>();
using(var reader = await mySqlCommand.ExecuteReaderAsync(CommandBehavior.CloseConnection))
{
while(await reader.ReadAsync())
myResult.Add(transform(reader));
}Is now simplified to this:
var myResult = await mySqlCommand.ToListAsync(transform);In order to keep connection open time to a minimum, some methods cache data before closing the connection and then subsequently applying the transformations as needed.
Queues all the data. Then using the provided type T entity, the data is coerced by which properties intersect with the ones available to the IDataReader.
Optionally a field to column override map can be passed as a parameter. If a column is set as null then that field is ignored (not applied to the model).
If all the columns in the database map exactly to a field: (A column that has no associated field/property is ignored.)
var people = cmd.Results<Person>();If the database fields don't map exactly:
var people = cmd.Results<Person>(
(Field:"FirstName", Column:"first_name"),
(Field:"LastName", Column:"last_name")));or
var people = cmd.Results<Person>(
("FirstName", "first_name"),
("LastName", "last_name"));or
var people = cmd.Results<Person>(new Dictionary<string,string>{
{"FirstName", "first_name"},
{"LastName", "last_name"});Queues all the data. Returns a QueryResult<Queue<object[]>> containing the requested data and column information. The .AsDequeueingMappedEnumerable() extension will iteratively convert the results to dictionaries for ease of access.
ResultsAsync<T>() is fully asynchronous from end-to-end but returns an IEnumerable<T> that although has fully buffered the all the data into memory, has deferred the transformation until enumerated. This way, the asynchronous data pipeline is fully complete before synchronously transforming the data.
Example:
// Returns true if the transaction is successful.
public static bool TryTransaction()
=> ConnectionFactory.Using(connection =>
// Open a connection and start a transaction.
connection.ExecuteTransactionConditional(transaction => {
// First procedure does some updates.
var count = transaction
.StoredProcedure("[Updated Procedure]")
.ExecuteNonQuery();
// Second procedure validates the results.
// If it returns true, then the transaction is committed.
// If it returns false, then the transaction is rolled back.
return transaction
.StoredProcedure("[Validation Procedure]")
.AddParam("@ExpectedCount", count)
.ExecuteScalar<bool>();
}));- All
.ConfigureAwait(true)are now.ConfigureAwait(false)as they should be. The caller will need to.ConfigureAwait(true)if they need to resume on the calling context. - Added
Open.Database.Extensions.MSSqlClientforMicrosoft.Data.SqlClientsupport. - .NET 8.0 added to targets to ensure potential compliation and performance improvements are available.
- Improved nullable integrity.
- Open.Database.Extensions meta-package is discontinued.
- .NET 9.0 added to targets to ensure potential compilation and performance improvements are available.
- Impelmented some .NET 8 and 9 specific features.
- Significant cleanup and simplifcation where possible.
A modernization and allocation-reduction pass. Source-compatible with 10.0 — existing code recompiles cleanly.
-
Target frameworks:
net10.0is now the primary/modern target.netstandard2.0andnetstandard2.1are retained as shimmed legacy paths (net8/net9 consumers use thenetstandard2.1build);Open.Database.Extensions.MSSqlClientalso targetsnet472. The explicitnet8.0/net9.0targets were dropped. -
Fewer allocations on the hot paths: case-insensitive column-to-property matching now uses
StringComparer.OrdinalIgnoreCase(andFrozenDictionaryonnet10.0) instead of allocating an upper-cased string per column; assorted per-query LINQ and dead code removed. -
Ergonomic field-mapping overrides:
Results<T>,ResultsAsync<T>,To<T>, etc. now accept target-typednew(...)and collection expressions:cmd.Results<Person>(new("FirstName", "first_name"), new("LastName", "last_name")); cmd.Results<Person>([new("FirstName", "first_name"), new("LastName", "last_name")]);
-
Modernized
params: ordinal helpers (Retrieve,AsEnumerable, …) acceptparams IEnumerable<int>/params IEnumerable<string>— any enumerable, not just arrays. -
Read-only inputs: several read-only
IList<T>parameters were widened toIReadOnlyList<T>(GetValuesFromOrdinals,EnumerateValuesFromOrdinals,ToDictionary). Arrays,List<T>,ImmutableArray<T>, etc. all still bind. (A custom type implementing onlyIList<T>— and not alsoIReadOnlyList<T>— would need to recompile; no BCL collection is affected.) -
Lower per-query overhead:
Transformer<T>caches its per-type reflection once instead of rebuilding it on every query; buffered/data-table paths pre-size collections and avoid redundantSelectiterators. -
Fixed a wasted-allocation / incorrect-return bug in
CopyToDBNullAsNull. -
Public API surface is now tracked with
Microsoft.CodeAnalysis.PublicApiAnalyzers, and unit-test coverage was substantially expanded.