Zymergi.Data 11.4.0-alpha

This is a prerelease version of Zymergi.Data.
dotnet add package Zymergi.Data --version 11.4.0-alpha
                    
NuGet\Install-Package Zymergi.Data -Version 11.4.0-alpha
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Zymergi.Data" Version="11.4.0-alpha" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Zymergi.Data" Version="11.4.0-alpha" />
                    
Directory.Packages.props
<PackageReference Include="Zymergi.Data" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Zymergi.Data --version 11.4.0-alpha
                    
#r "nuget: Zymergi.Data, 11.4.0-alpha"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Zymergi.Data@11.4.0-alpha
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Zymergi.Data&version=11.4.0-alpha&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Zymergi.Data&version=11.4.0-alpha&prerelease
                    
Install as a Cake Tool

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 shared DbConnection: 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. Close and Dispose both return the connection to the pool.
  • Whoever opens a connection closes it. OpenScopeAsync and DbUnitOfWork follow this rule: they close only a connection they opened.
  • Parallel work uses Task.WhenAll with a connection per task. A factory-built repository from Zymergi.Data.MariaDb takes a new connection for each operation outside a unit of work, so one instance can serve parallel tasks. Never share a connection or a DbUnitOfWork across tasks.
  • Set pool limits in the connection string, for example MySqlConnector Maximum Pool Size, Minimum Pool Size, Connection Lifetime, Connection Idle Timeout, Connection Timeout, and Default Command Timeout. Size the pool for peak concurrent operations, not for requests.

Transactions

  • Use DbUnitOfWork only 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.
  • DbUnitOfWork uses the provider's default isolation level (REPEATABLE READ on MariaDB/InnoDB). It has no isolation-level option. If you need another level, call conn.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct) yourself.

Async and cancellation

  • Async all the way. Pass the endpoint's CancellationToken (HttpContext.RequestAborted) to every call. Readers use ReadAsync(ct).
  • Never block with .Result or .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.AddList binds an IN list. An empty list returns (NULL), which matches no row with IN. With NOT 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 keyset WHERE uid > ?last ORDER BY uid LIMIT ?n for deep pages).
  • Avoid N+1 queries: load related rows with one IN query.
  • Batch inserts: one multi-row INSERT, inside a DbUnitOfWork when it must be atomic.
  • Set DbCommand.CommandTimeout for a known long query, or Default Command Timeout in 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) calls GetOrdinal on every row.
  • ExecuteReaderAsync<T>() maps by column name with reflection, using BuildMapper<T> so each column's property is found once per reader.
  • Results are buffered into a list. For very large results, write your own DbDataReader loop and process rows as they arrive.

Retry

  • TryOpenAsync, TryCloseAsync, OpenScopeAsync, and DbUnitOfWork.CreateAsync retry only a TimeoutException, an IOException, or a DbException whose IsTransient is 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, or MariaRepositoryBase<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() and app.UseExceptionHandler(). Map a transient DbException to 503 in an IExceptionHandler. Never return SQL or connection strings to the client.
  • Health check: builder.Services.AddHealthChecks().AddCheck<DbHealthCheck>("db") and app.MapHealthChecks("/healthz"), where the check opens a factory connection and runs SELECT 1.
  • OpenTelemetry: MySqlConnector publishes an ActivitySource and a meter named MySqlConnector. Add them with .WithTracing(t => t.AddSource("MySqlConnector")) and .WithMetrics(m => m.AddMeter("MySqlConnector")).
  • Caching: cache read-mostly queries with HybridCache (builder.Services.AddHybridCache(), then cache.GetOrCreateAsync(key, async ct => ..., cancellationToken: ct)). It runs the factory once per key under concurrent misses. IMemoryCache.GetOrCreateAsync does 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 IDbConnectionFactory and 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}), or Data Source=name;Mode=Memory;Cache=Shared and 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

  • ExecuteAsync on a connection inside a unit of work must get uow.Transaction, or the provider rejects the command (MySqlConnector requires the transaction to be set).
  • DbUnitOfWork does not dispose the connection. Dispose it yourself (await using var conn before the unit of work).
  • ILogRepository is obsolete and goes away in 12.0. Log with ILogger<T>.
  • IDbConnectionFactory.GetConnection throws KeyNotFoundException when 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 DbException was retried for about 3 s.
  • ILogger overloads for TryOpenAsync, TryCloseAsync, OpenScopeAsync, and DbUnitOfWork.CreateAsync.
  • ParameterBag.AddList for IN lists.
  • AddDbConnectionFactory registers the singleton factory.
  • Readers use ReadAsync(ct). New MappingExtensionMethods.BuildMapper<T>.

11.3.0-alpha

  • Breaking: these types moved from Zymergi.Core into this package. The namespace Zymergi.Data did not change. Add a Zymergi.Data package reference if you used them with only Zymergi.Core.

Source: bitbucket.org/zymergy/zymergi.saas

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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