Zymergi.Data
11.4.0-alpha
dotnet add package Zymergi.Data --version 11.4.0-alpha
NuGet\Install-Package Zymergi.Data -Version 11.4.0-alpha
<PackageReference Include="Zymergi.Data" Version="11.4.0-alpha" />
<PackageVersion Include="Zymergi.Data" Version="11.4.0-alpha" />
<PackageReference Include="Zymergi.Data" />
paket add Zymergi.Data --version 11.4.0-alpha
#r "nuget: Zymergi.Data, 11.4.0-alpha"
#:package Zymergi.Data@11.4.0-alpha
#addin nuget:?package=Zymergi.Data&version=11.4.0-alpha&prerelease
#tool nuget:?package=Zymergi.Data&version=11.4.0-alpha&prerelease
Zymergi.Data
ADO.NET helpers for Zymergi apps. It is a set of extension methods, not an ORM. It builds parameterized commands, opens and closes connections with a transient-only retry, runs one transaction per unit of work, and maps IDataRecord rows in code.
Targets .NET 10. Depends on Zymergi.Core and Microsoft.Extensions.DependencyInjection.Abstractions. Namespace Zymergi.Data. Zymergi.Data.MariaDb, Zymergi.Social, Zymergi.Search.Sqlite, and Zymergi.AspNetCore reference it, so they bring it in.
Install
dotnet add package Zymergi.Data
dotnet add package MySqlConnector # or the ADO.NET provider you use
This package does not ship a provider. The host references one and names it in configuration.
Register in Program.cs
{
"DbProviderFactorySettings": [
{ "Invariant": "mysql", "Type": "MySqlConnector.MySqlConnectorFactory, MySqlConnector", "Name": "mysql", "Description": "MySqlConnector" }
],
"ConnectionStringSettings": [
{ "Name": "app", "ProviderName": "mysql", "ConnectionString": "" }
]
}
ProviderName must match an Invariant. AppSettingsDbConnectionFactory registers each provider with DbProviderFactories when it is built. Keep the real connection string out of appsettings.json:
dotnet user-secrets set "ConnectionStringSettings:0:ConnectionString" "Server=db;Database=app;User ID=app;Password=...;Maximum Pool Size=50"
# production: environment variable ConnectionStringSettings__0__ConnectionString, or a vault configuration provider
using Zymergi.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbConnectionFactory(builder.Configuration); // singleton IDbConnectionFactory
AddDbConnectionFactory uses TryAddSingleton, so a second call adds nothing. Do not register a DbConnection (scoped or singleton). GetConnection(name) returns a new, closed connection each time.
Use it
Minimal API endpoint. Pass the request's CancellationToken all the way down:
app.MapGet("/products/{id:long}", async (long id, ProductQueries q, CancellationToken ct) =>
await q.GetAsync(id, ct) is { } p ? Results.Ok(p) : Results.NotFound());
Service. One connection per operation: create it late, dispose it early:
using System.Data;
using Zymergi.Core.Utilities;
using Zymergi.Data;
public sealed record ProductDto(long Id, string Name, decimal Price);
public sealed class ProductQueries(IDbConnectionFactory factory, ILogger<ProductQueries> logger)
{
static ProductDto Map(IDataRecord r) =>
new(r.GetInt64(0), r.GetString(1), r.GetDecimal(2));
public async Task<ProductDto?> GetAsync(long id, CancellationToken ct)
{
await using var conn = factory.GetConnection("app");
var rows = await conn.QueryAsync(
"SELECT uid, name, price FROM product WHERE uid = ?id",
Map, [new("?id", id)], cancellationToken: ct);
return rows.Count == 0 ? null : rows[0];
}
public async Task<IReadOnlyList<ProductDto>> GetManyAsync(IReadOnlyCollection<long> ids, CancellationToken ct)
{
var p = new ParameterBag('?');
string inList = p.AddList(ids); // "(?p0,?p1,...)" or "(NULL)" when empty
await using var conn = factory.GetConnection("app");
return await conn.QueryAsync($"SELECT uid, name, price FROM product WHERE uid IN {inList}",
Map, p.Parameters, cancellationToken: ct);
}
}
QueryAsync, ExecuteAsync, and ScalarAsync open the connection only when it is closed and close it again only if they opened it. To run several commands on one open connection, open it yourself:
await using var conn = factory.GetConnection("app");
await using (await conn.OpenScopeAsync(logger, ct))
{
int count = await conn.ScalarAsync<int>("SELECT COUNT(*) FROM product", cancellationToken: ct);
var page = await conn.QueryAsync("SELECT uid, name, price FROM product ORDER BY uid LIMIT 20", Map, cancellationToken: ct);
}
Atomic write across tables or repositories:
await using var conn = factory.GetConnection("app");
await using var uow = await DbUnitOfWork.CreateAsync(conn, logger, ct);
await conn.ExecuteAsync("UPDATE stock SET qty = qty - ?n WHERE sku = ?sku",
[new("?n", n), new("?sku", sku)], uow.Transaction, ct);
using (var cmd = uow.BuildCommand("INSERT INTO stock_log (sku, delta) VALUES (?sku, ?d)",
[new("?sku", sku), new("?d", -n)]))
{
await cmd.ExecuteNonQueryAsync(ct);
}
await uow.CommitAsync(ct); // dispose without commit rolls back
Parallel reads use one connection each:
async Task<IReadOnlyList<ProductDto>> Read(string sql)
{
await using var c = factory.GetConnection("app");
return await c.QueryAsync(sql, Map, cancellationToken: ct);
}
var both = await Task.WhenAll(Read("SELECT ... a"), Read("SELECT ... b"));
Best practices
Connections and pooling
- One singleton
IDbConnectionFactory. Never a scoped or sharedDbConnection: one connection cannot run two commands at once (MySqlConnector throws), and a scoped connection holds a pool slot for the whole request. - Connection per operation. Open late, dispose early.
CloseandDisposeboth return the connection to the pool. - Whoever opens a connection closes it.
OpenScopeAsyncandDbUnitOfWorkfollow this rule: they close only a connection they opened. - Parallel work uses
Task.WhenAllwith a connection per task. A factory-built repository fromZymergi.Data.MariaDbtakes a new connection for each operation outside a unit of work, so one instance can serve parallel tasks. Never share a connection or aDbUnitOfWorkacross tasks. - Set pool limits in the connection string, for example MySqlConnector
Maximum Pool Size,Minimum Pool Size,Connection Lifetime,Connection Idle Timeout,Connection Timeout, andDefault Command Timeout. Size the pool for peak concurrent operations, not for requests.
Transactions
- Use
DbUnitOfWorkonly when several writes must succeed or fail together. A single statement is already atomic. - Keep a transaction short. Do no HTTP calls, file I/O, or user waits inside it.
DbUnitOfWorkuses the provider's default isolation level (REPEATABLE READ on MariaDB/InnoDB). It has no isolation-level option. If you need another level, callconn.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct)yourself.
Async and cancellation
- Async all the way. Pass the endpoint's
CancellationToken(HttpContext.RequestAborted) to every call. Readers useReadAsync(ct). - Never block with
.Resultor.Wait().
SQL
- Always use parameters. Never concatenate user input into SQL. A sort column or table name cannot be a parameter: check it against an allow list.
ParameterBag.AddListbinds an IN list. An empty list returns(NULL), which matches no row withIN. WithNOT IN,(NULL)matches no row either, which is usually wrong: skip the condition when the list is empty.- Select only the columns you need. Avoid
SELECT *. - Page every list query (
LIMIT/OFFSET, or keysetWHERE uid > ?last ORDER BY uid LIMIT ?nfor deep pages). - Avoid N+1 queries: load related rows with one
INquery. - Batch inserts: one multi-row
INSERT, inside aDbUnitOfWorkwhen it must be atomic. - Set
DbCommand.CommandTimeoutfor a known long query, orDefault Command Timeoutin the connection string. - Index the columns you filter, join, and sort on. Check plans with
EXPLAIN.
Mapping
- Map rows to DTOs in code. Read by ordinal in hot paths (
r.GetInt64(0)).Get<T>(name)callsGetOrdinalon every row. ExecuteReaderAsync<T>()maps by column name with reflection, usingBuildMapper<T>so each column's property is found once per reader.- Results are buffered into a list. For very large results, write your own
DbDataReaderloop and process rows as they arrive.
Retry
TryOpenAsync,TryCloseAsync,OpenScopeAsync, andDbUnitOfWork.CreateAsyncretry only aTimeoutException, anIOException, or aDbExceptionwhoseIsTransientis true. Any other error throws at once.- The default budget is 5 s with a 1 s first wait, and the wait doubles: try, wait 1 s, try, wait 2 s, try, then throw. That is three tries and 3 s of waits. A budget too small for one try throws
InvalidOperationException. - Cancellation stops the waits and throws
OperationCanceledException. - Pass an
ILogger(the overloads, orMariaRepositoryBase<T>.Logger) to log one warning per failed try. - Only the open and close are retried, never a command. Do not blindly retry a write that is not idempotent: you may apply it twice.
ASP.NET Core host (these are host features, not part of this package)
- Errors:
builder.Services.AddProblemDetails()andapp.UseExceptionHandler(). Map a transientDbExceptionto 503 in anIExceptionHandler. Never return SQL or connection strings to the client. - Health check:
builder.Services.AddHealthChecks().AddCheck<DbHealthCheck>("db")andapp.MapHealthChecks("/healthz"), where the check opens a factory connection and runsSELECT 1. - OpenTelemetry: MySqlConnector publishes an
ActivitySourceand a meter namedMySqlConnector. Add them with.WithTracing(t => t.AddSource("MySqlConnector"))and.WithMetrics(m => m.AddMeter("MySqlConnector")). - Caching: cache read-mostly queries with
HybridCache(builder.Services.AddHybridCache(), thencache.GetOrCreateAsync(key, async ct => ..., cancellationToken: ct)). It runs the factory once per key under concurrent misses.IMemoryCache.GetOrCreateAsyncdoes not protect against that. - Output caching (
AddOutputCache,.CacheOutput(...)) and rate limiting (AddRateLimiter,.RequireRateLimiting(...)) protect the database from bursts.
public sealed class DbHealthCheck(IDbConnectionFactory factory) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
{
try
{
await using var conn = factory.GetConnection("app");
await conn.ScalarAsync<int>("SELECT 1", cancellationToken: ct);
return HealthCheckResult.Healthy();
}
catch (DbException ex)
{
return HealthCheckResult.Unhealthy("database unreachable", ex);
}
}
}
Testing
- Unit tests: depend on
IDbConnectionFactoryand give it a fake, or point it at SQLite. An in-memory SQLite database (Data Source=:memory:) exists only while one connection stays open. Use a temp file (Data Source={tempPath}), orData Source=name;Mode=Memory;Cache=Sharedand keep one connection open for the test. - Integration tests: run MariaDB in Testcontainers or a disposable local instance. Never test against production.
- Keep test credentials in user-secrets or environment variables, not in committed files.
Gotchas
ExecuteAsyncon a connection inside a unit of work must getuow.Transaction, or the provider rejects the command (MySqlConnector requires the transaction to be set).DbUnitOfWorkdoes not dispose the connection. Dispose it yourself (await using var connbefore the unit of work).ILogRepositoryis obsolete and goes away in 12.0. Log withILogger<T>.IDbConnectionFactory.GetConnectionthrowsKeyNotFoundExceptionwhen the name or provider is not configured.
API reference
Interfaces
| Type | Purpose |
|---|---|
IDbConnectable |
Contract for classes that own a DbConnection and an optional DbUnitOfWork |
IDbConnectionFactory |
Creates a new, closed DbConnection by connection name (GetConnection) |
IDbRegistry |
Database-backed IRegistry exposing table name and primary key metadata |
IDbRegistrableRepository<T> |
Database-backed IRegistrableRepository with IDbRegistry support |
ILogRepository |
Obsolete. Repository contract for persisting and querying log records. Namespace Zymergi.Logging. It extends IDbConnectable, so it ships with this package. Removal is planned for 12.0 |
Classes
| Type | Purpose |
|---|---|
AppSettingsDbConnectionFactory |
IDbConnectionFactory that reads DbProviderFactorySettings and ConnectionStringSettings from IConfiguration |
DbUnitOfWork |
Async all-or-nothing transaction wrapper over DbConnection (create via CreateAsync) |
OpenConnectionScopeAsync |
Opens a connection for a scope and closes it on dispose only if the scope opened it |
ParameterBag |
Collects named parameters for generated SQL. AddList binds an IN list with unique names; an empty list gives (NULL) |
DbPrimaryKeyAttribute |
Marks a property as the database primary key |
DbGeneratedAttribute |
Marks database-generated properties excluded from INSERT/UPDATE |
DbRequiredAttribute |
Marks properties that cannot be null |
StartTimeAttribute |
Marks property as beginning of a searchable timespan |
EndTimeAttribute |
Marks property as end of a searchable timespan |
DbGenerateMode |
Enum specifying column value generation (None, AutoIncrement) |
Extension methods
| Type | Purpose |
|---|---|
DbCommandExtensionMethods |
Parameterize, AddParameter, and ExecuteReaderAsync on DbCommand |
DbConnectionExtensionMethods |
Async extensions for DbConnection (TryOpenAsync, TryCloseAsync, BuildCommand, QueryAsync, ExecuteAsync, ScalarAsync). TryOpenAsync and TryCloseAsync retry a timeout, an I/O error, or a transient DbException; an overload that takes an ILogger writes one warning for each failed try |
OpenConnectionScopeExtensions |
OpenScopeAsync on DbConnection, with an optional ILogger overload |
IDbCommandExtensionMethods |
GetParametersAsString for command diagnostics |
SelectSqlExtensionMethods |
Builds SELECT statements from KeyValuePair collections |
InsertSqlExtensionMethods |
Builds INSERT statements from KeyValuePair collections |
UpdateSqlExtensionMethods |
Builds UPDATE statements from KeyValuePair collections |
DbExpressionExtensionMethods |
Data record column definitions and element extraction |
DbExceptionExtensionMethods |
Elaborates exceptions with DbCommand diagnostic data |
DataServiceCollectionExtensions |
AddDbConnectionFactory registers AppSettingsDbConnectionFactory as the singleton IDbConnectionFactory |
MappingExtensionMethods |
Maps IDataRecord rows to objects and manipulates properties via reflection |
DataRecordExtensionMethods (Get<T>, GetNullable<T>) stays in Zymergi.Core.Utilities, because Core models map rows with it.
Version notes
11.4.0-alpha
- Retry is transient-only. Before, every
DbExceptionwas retried for about 3 s. ILoggeroverloads forTryOpenAsync,TryCloseAsync,OpenScopeAsync, andDbUnitOfWork.CreateAsync.ParameterBag.AddListfor IN lists.AddDbConnectionFactoryregisters the singleton factory.- Readers use
ReadAsync(ct). NewMappingExtensionMethods.BuildMapper<T>.
11.3.0-alpha
- Breaking: these types moved from
Zymergi.Coreinto this package. The namespaceZymergi.Datadid not change. Add aZymergi.Datapackage reference if you used them with onlyZymergi.Core.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.12)
- Zymergi.Core (>= 11.4.0-alpha)
NuGet packages (4)
Showing the top 4 NuGet packages that depend on Zymergi.Data:
| Package | Downloads |
|---|---|
|
Zymergi.Data.MariaDb
MariaDB repository implementations for Zymergi entities. |
|
|
Zymergi.AspNetCore
ASP.NET Core controllers, authentication filters, and startup extensions for Zymergi. |
|
|
Zymergi.Social
The Social domain (users, groups, favorites, submissions, comments) as models and repository interfaces over Zymergi.Core. |
|
|
Zymergi.Search.Sqlite
SQLite implementation of the engine-neutral faceted-search contracts for Zymergi. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 11.4.0-alpha | 117 | 11/16/2026 |
| 11.3.0-alpha | 98 | 11/12/2026 |