Zymergi.Data.MariaDb
11.4.0-alpha
dotnet add package Zymergi.Data.MariaDb --version 11.4.0-alpha
NuGet\Install-Package Zymergi.Data.MariaDb -Version 11.4.0-alpha
<PackageReference Include="Zymergi.Data.MariaDb" Version="11.4.0-alpha" />
<PackageVersion Include="Zymergi.Data.MariaDb" Version="11.4.0-alpha" />
<PackageReference Include="Zymergi.Data.MariaDb" />
paket add Zymergi.Data.MariaDb --version 11.4.0-alpha
#r "nuget: Zymergi.Data.MariaDb, 11.4.0-alpha"
#:package Zymergi.Data.MariaDb@11.4.0-alpha
#addin nuget:?package=Zymergi.Data.MariaDb&version=11.4.0-alpha&prerelease
#tool nuget:?package=Zymergi.Data.MariaDb&version=11.4.0-alpha&prerelease
Zymergi.Data.MariaDb
MariaDB/MySQL repository base classes for Zymergi entities: CRUD, soft delete, paging, batch import, a handle registry, and change events. Raw ADO.NET with SQL built by Zymergi.Data helpers, not an ORM.
Targets .NET 10. Depends on Zymergi.Core and Zymergi.Data. The host adds the provider (MySqlConnector).
Install
dotnet add package Zymergi.Data.MariaDb
dotnet add package MySqlConnector
Register in Program.cs
Configure the provider and connection string as described in the Zymergi.Data README, then:
using Zymergi.Data;
builder.Services.AddDbConnectionFactory(builder.Configuration); // singleton
builder.Services.AddTransient<ProductRepository>(sp =>
new ProductRepository(sp.GetRequiredService<IDbConnectionFactory>(), "app")
{
Logger = sp.GetRequiredService<ILogger<ProductRepository>>()
});
Use the (IDbConnectionFactory, string) constructor. Each operation outside a unit of work takes a new connection from the factory and returns it to the pool when it ends, so parallel calls on one instance never share a connection. Do not register a scoped DbConnection and pass it to repositories.
Use it
Entity and repository:
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using Zymergi.Core.Models;
using Zymergi.Core.Utilities;
using Zymergi.Data;
using Zymergi.Data.MariaDb;
public sealed class Product : EntityBase
{
public Product() { }
public Product(IDataRecord r) : base(r)
{
Name = r.Get<string>("name") ?? "";
Price = r.Get<decimal>("price");
}
public string Name { get; set; } = "";
public decimal Price { get; set; }
public override NameValueCollection ToNvc(bool omitCreateUpdateTimestamps = false)
{
var nvc = new NameValueCollection
{
{ "uid", Uid > 0 ? Uid.ToString(CultureInfo.InvariantCulture) : null },
{ "name", Name },
{ "price", Price.ToString(CultureInfo.InvariantCulture) },
{ "dtLastDeleted", DtLastDeleted?.ToString("yyyy-MM-dd HH:mm:ss") },
};
if (!omitCreateUpdateTimestamps)
{
nvc.Add("dtCreated", DtCreated.ToString("yyyy-MM-dd HH:mm:ss"));
nvc.Add("dtLastUpdated", DtLastUpdated.ToString("yyyy-MM-dd HH:mm:ss"));
}
return nvc;
}
}
public sealed class ProductRepository : MariaRepositoryBase<Product>
{
public ProductRepository(IDbConnectionFactory factory, string name) : base(factory, name) { }
public ProductRepository(DbUnitOfWork uow) : base(uow) { }
public override string TABLE_NAME => "product";
public override string PRIMARY_KEY_NAME => "uid";
protected override Func<IDataRecord, Product> mapMethod => r => new Product(r);
protected override string CREATE_TABLE_SQL => "CREATE TABLE `product` (" +
" `uid` BIGINT NOT NULL AUTO_INCREMENT," +
" `dtCreated` DATETIME NOT NULL DEFAULT UTC_TIMESTAMP()," +
" `dtLastUpdated` DATETIME NOT NULL DEFAULT UTC_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()," +
" `dtLastDeleted` DATETIME NULL DEFAULT NULL," +
" `name` VARCHAR(200) NOT NULL," +
" `price` DECIMAL(10,2) NOT NULL," +
" PRIMARY KEY (`uid`), INDEX `i_product_name` (`name`));";
// A custom query: project only what you need and set a timeout.
public Task<IEnumerable<string>> GetNamesCheaperThanAsync(decimal max, CancellationToken ct) =>
execQueryAsync(async cmd =>
{
cmd.CommandTimeout = 10;
return await cmd.ExecuteReaderAsync(r => r.GetString(0), ct);
},
$"SELECT name FROM {TABLE_NAME} WHERE price < ?max AND dtLastDeleted IS NULL ORDER BY name LIMIT 100",
new Dictionary<string, object> { { "max", max } }, ct);
}
Controller:
[ApiController]
[Route("products")]
public sealed class ProductsController(ProductRepository products) : ControllerBase
{
[HttpGet]
public async Task<IEnumerable<Product>> List(int limit = 20, int offset = 0, CancellationToken ct = default) =>
await products.GetAsync(Math.Clamp(limit, 1, 100), offset, "name", "asc", ct);
[HttpGet("{id:long}")]
public async Task<ActionResult<Product>> Get(long id, CancellationToken ct) =>
await products.GetAsync(id, ct) is { } p ? p : NotFound();
}
Atomic write across repositories: build each repository on the same DbUnitOfWork:
await using var conn = factory.GetConnection("app");
await using var uow = await DbUnitOfWork.CreateAsync(conn, logger, ct);
var products = new ProductRepository(uow);
var prices = new PriceHistoryRepository(uow);
var added = await products.AddAsync(product, ct);
await prices.AddAsync(new PriceHistory { ProductUid = added.Uid, Price = added.Price }, ct);
await uow.CommitAsync(ct);
Parallel reads on one factory-built instance each get their own connection:
var products = new ProductRepository(factory, "app");
await Task.WhenAll(products.GetAsync(1, ct), products.GetAsync(2, ct));
Best practices
- Follow the
Zymergi.DataREADME for connections, transactions, async, SQL, retry, and the host features (ProblemDetails, health checks, OpenTelemetry, caching, rate limiting). - A factory-built instance is safe for parallel calls: each operation outside a unit of work uses its own connection. Only a unit of work that is active in the call flow makes operations share its connection and transaction, so never share a
DbUnitOfWorkacross tasks. Register repositories as transient. - Use the batch reads:
GetAsync(IEnumerable<long>)loads many rows in oneINquery (no N+1).ImportAsync(entities, replaceIfExists)writes all rows in one multi-statement command (INSERT IGNOREorON DUPLICATE KEY UPDATE); wrap it in aDbUnitOfWorkif it must be all-or-nothing. - Page with
GetAsync(limit, offset, sortByColumn, sortOrder).SortClauseValidatoraccepts only known column names, so user input cannot inject SQL there. For deep pages write a keyset query withexecQueryAsync. - Prefer
RemoveAsync/RestoreAsync(soft delete) andEmptyTrashAsync(days)overDeleteAsync. - Set
Loggerto log each failed open and each retry wait. - Run
InitializeAsync(create table if missing) from a migration step or a one-off admin task, not on every request.
Testing
- Unit-test services against an interface (for example
IRepository<Product>) with a fake. - Integration-test the repository against MariaDB in Testcontainers. Never against production. No test in this repository connects to a database during a unit run.
Gotchas
- The base class reads with
SELECT *. It has no column projection. For hot or wide tables, write a custom query withexecQueryAsync. - There is no per-repository command timeout setting. Set
cmd.CommandTimeoutinsideexecQueryAsync, orDefault Command Timeoutin the connection string. AddAsyncon an auto-increment table runs theINSERT, then reads the row back withLAST_INSERT_ID(), which belongs to the session. A factory-built instance runs both in one new unit of work on one connection. On theDbConnectionconstructor, outside a unit of work, the connection is closed and reopened between the two: runAddAsyncinside aDbUnitOfWork, or open the connection first (await using (await repo.DbConnection.OpenScopeAsync(ct)) { ... }).- The
DbConnectionandDbUnitOfWorkconstructors keep their 11.x behavior: every operation outside a unit of work uses that one connection. A parallel call on the same instance runs on it even when it does not see another flow's unit of work, so SQLite runs it inside the open transaction and MySqlConnector refuses it. Use the factory constructor, or one instance per concurrent call flow. TryAddAsyncbehaves likeAddAsync: it throws on a duplicate key.- The repository does not implement
IDisposable. Its connection is closed between operations, so it does not hold a pool slot. - On a factory-built registrable repository, the registry is factory-built too, so
Registry.DbConnectionis a different connection fromDbConnection. A unit of work set on the repository is passed to the registry. MariaLogRepositoryand the[handle]indexers are obsolete and go away in 12.0. UseILogger<T>,GetAsync(handle), andUpdateAsync(handle, entity).
Included repositories
| Type | Purpose |
|---|---|
MariaRepositoryBase<T> |
CRUD, soft-delete, restore, paging, change events |
SortClauseValidator |
Checks a sort column against the known names. A blank or unknown direction becomes ASC |
MariaRegistrableRepositoryBase<T> |
Handle lookup via the registry table. The [handle] indexer is obsolete and blocks the calling thread. Use GetAsync and UpdateAsync |
MariaRegistry |
Central handle registry. The [handle] indexer is obsolete. Use GetAsync and UpdateAsync |
MariaLogRepository |
Obsolete. Immutable log entries |
Version notes
11.4.0-alpha
- New constructors
MariaRepositoryBase<T>(IDbConnectionFactory, string)andMariaRegistrableRepositoryBase<T>(IDbConnectionFactory, string). DeleteAsync(IEnumerable<long>)with an empty list returns 0 and runs no SQL.Loggerproperty logs failed opens and waits.- The registrable
UpdateAsynckeeps its transaction to its own call flow. - A factory-built repository takes a new connection for each operation outside a unit of work, so a parallel call on the same instance no longer shares the connection or the transaction of another flow.
AddAsyncruns itsINSERTand read-back in one new unit of work. TheDbConnectionconstructor keeps its behavior. - New constructor
MariaRegistry(IDbConnectionFactory, string). The factory-built registrable repository builds its registry with it. - Readers use
ReadAsync(ct).
Article repositories live in Zymergi.Articles.MariaDb, and social repositories in Zymergi.Social.MariaDb. The build does not pack those projects.
| 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
- Zymergi.Core (>= 11.4.0-alpha)
- Zymergi.Data (>= 11.4.0-alpha)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on Zymergi.Data.MariaDb:
| Package | Downloads |
|---|---|
|
Zymergi.Social.MariaDb
MariaDB persistence and DI registration for the Zymergi Social domain. |
|
|
Zymergi.Articles.MariaDb
MariaDB persistence and DI registration for the Zymergi Article domain. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 11.4.0-alpha | 60 | 11/16/2026 |
| 11.3.0-alpha | 69 | 11/12/2026 |
| 11.2.0-alpha | 70 | 11/2/2026 |
| 11.1.1-alpha | 96 | 10/4/2026 |
| 11.1.0-alpha | 112 | 10/1/2026 |
| 11.0.6-alpha | 129 | 7/10/2026 |
| 11.0.5-alpha | 146 | 7/9/2026 |
| 11.0.4-alpha | 103 | 7/6/2026 |
| 11.0.3-alpha | 93 | 7/6/2026 |
| 11.0.2-alpha | 131 | 6/30/2026 |
| 11.0.1-alpha | 117 | 6/30/2026 |
| 11.0.0-alpha | 107 | 6/29/2026 |