LowCodeHub.Dapper
0.1.0
dotnet add package LowCodeHub.Dapper --version 0.1.0
NuGet\Install-Package LowCodeHub.Dapper -Version 0.1.0
<PackageReference Include="LowCodeHub.Dapper" Version="0.1.0" />
<PackageVersion Include="LowCodeHub.Dapper" Version="0.1.0" />
<PackageReference Include="LowCodeHub.Dapper" />
paket add LowCodeHub.Dapper --version 0.1.0
#r "nuget: LowCodeHub.Dapper, 0.1.0"
#:package LowCodeHub.Dapper@0.1.0
#addin nuget:?package=LowCodeHub.Dapper&version=0.1.0
#tool nuget:?package=LowCodeHub.Dapper&version=0.1.0
LowCodeHub.Dapper
A Dapper-first data-access package for SQL Server and PostgreSQL. Its application boundary is a
concrete, typed DapperDbContext with context-owned DapperSet<TEntity> properties and
an independent IQueryable provider; it has no EF Core dependency. Raw Dapper commands, native
provider values, type handlers, unbuffered streams, multiple result sets, owned sessions, and
transactions remain available without injecting repository infrastructure into feature services.
Quickstart
using LowCodeHub.Dapper.Abstractions;
using LowCodeHub.Dapper.Extensions;
using LowCodeHub.Dapper.Querying;
// 1. A context with one set. Conventions map public properties to the table "Product".
public sealed class CatalogDatabase : DapperDbContext
{
public DapperSet<Product> Products => Set<Product>();
}
// 2. Register it (SQL Server shown; AddDapperPostgreSql is identical).
builder.Services.AddDapperSqlServer<CatalogDatabase>(
builder.Configuration.GetConnectionString("Catalog")!);
// 3. Inject the context and query with LINQ, translated to parameterized SQL.
public sealed class ProductReader(CatalogDatabase db)
{
public Task<List<Product>> ActiveAsync(int[] ids, CancellationToken ct)
=> db.Products.Query()
.Where(p => p.IsActive && ids.Contains(p.Id)) // IN / = ANY
.OrderBy(p => p.Name)
.ToListAsync(ct);
}
Registration validates the connection settings immediately, registers a readiness health check
(dapper-CatalogDatabase) and emits OpenTelemetry traces/metrics from LowCodeHub.Dapper.
Everything below is optional.
Registration and mapping
Put entity mappings and named sets on the context class, then inject the concrete type:
using LowCodeHub.Dapper.Abstractions;
using LowCodeHub.Dapper.Mapping;
public sealed class CatalogDatabase : DapperDbContext
{
public DapperSet<Product> Products => Set<Product>();
protected override void OnModelCreating(DapperModelBuilder model)
{
model.Entity<Product>(entity =>
{
entity.ToTable("products", "catalog");
entity.HasKey(product => product.Id, generatedOnAdd: true);
entity.Property(product => product.Id, "id");
entity.Property(product => product.Name, "product_name");
entity.Property(product => product.IsActive, "is_active");
});
}
}
Register its provider and connection in DI. Three equivalent styles are available:
using LowCodeHub.Dapper.Extensions;
// Connection string (+ optional options lambda)
builder.Services.AddDapperPostgreSql<CatalogDatabase>(connectionString,
options => options.CommandTimeoutSeconds = 30);
// Full options lambda
builder.Services.AddDapperPostgreSql<CatalogDatabase>(options =>
{
builder.Configuration.GetSection("Dapper:Catalog").Bind(options); // bind and then adjust
options.CommandTimeoutSeconds = 30;
});
// IConfiguration section (default "Dapper:SqlServer" / "Dapper:PostgreSql")
builder.Services.AddDapperPostgreSql<CatalogDatabase>(builder.Configuration, "Dapper:Catalog");
| Option | Default | Purpose |
|---|---|---|
ConnectionString / UseDataSource / UseConnectionFactory |
— | Exactly one connection source is required. |
CommandTimeoutSeconds |
provider default | Default timeout for every command. |
SlowQueryThreshold |
1 s | Marks slow commands in traces/metrics. |
IncludeCommandTextInDiagnostics |
false |
Adds SQL text to activities (may contain literals from raw SQL). |
EnableQueryPlanCache |
true |
Caches parsing of reused expression instances and interns generated SQL. |
UseAnsiStringParameters |
false |
SQL Server: send LINQ/specification strings as varchar for varchar columns. |
JsonSerializerOptions |
JsonSerializerOptions.Default |
Serializer for Json<T>; process-wide (see JSON). |
MaxBatchSize |
1000 | Maximum rows per batched insert command (also bounded by provider parameter limits). |
RegisterHealthCheck |
true |
Adds the dapper-{Context} readiness check (tags dapper, provider, readiness). |
AddTypeHandler, AddMethodTranslator |
— | Process-wide Dapper handlers; opt-in LINQ method translations. |
Misconfiguration (no/multiple connection sources, non-positive timeout, threshold or batch size, a context registered twice, conflicting JSON serializer instances) throws during registration.
A configured DbDataSource is preferred for Npgsql; an application factory supports access
tokens, credential rotation, and per-request tenant routing:
options.UseDataSource(npgsqlDataSource); // the application owns and disposes the data source
// Or, resolved in the consuming context's DI scope:
options.UseConnectionFactory(services =>
services.GetRequiredService<ITenantDatabaseRouter>().CreateConnection());
Typed contexts and context-owned sets
The concrete context is always the application dependency. DapperSet<TEntity> keeps repository
and specification operations behind that database boundary, like DbSet<TEntity> without EF
tracking:
public sealed class ProductReader(CatalogDatabase database)
{
public Task<IReadOnlyList<ProductSummary>> ListAsync(
string namePrefix,
CancellationToken cancellationToken)
=> database.Products.ListAsync(
new ActiveProductSummaries(namePrefix), cancellationToken);
public Task<List<Product>> QueryAsync(CancellationToken cancellationToken)
=> database.Query<Product>()
.Where(product => product.IsActive)
.OrderBy(product => product.Name)
.ToListAsync(cancellationToken);
}
Use database.Set<TEntity>() directly when a named property adds no clarity. Repository
infrastructure is internal; application constructors receive only their concrete database type.
This leaves one database dependency in an application repository:
public sealed class PaymentRepository(PaymentDatabase database) : IPaymentRepository
{
public Task<IReadOnlyList<GetSchoolConsumerBundlesResponse>> ListAsync(
CancellationToken cancellationToken)
=> database.Bundles.ListAsync(
new SchoolConsumerBundlesSpecification(), cancellationToken);
}
OnModelCreating is evaluated once and cached for the context type. Keep it deterministic and do
not read scoped request/tenant state there. The concrete context itself is scoped and may receive
normal application services through constructor injection.
When one application talks to multiple databases, providers, tenant groups, or read/write roles, define a separate context class for each. Every context has its own connection source, provider dialect, timeout, mapping model, and application translators. The same entity CLR type may map to different tables in different contexts.
OpenSessionAsync and InTransactionAsync return IDapperSession. The session was opened by the
concrete typed context and remains bound to its exact
connection, provider, mapping model, and current transaction:
await catalog.InTransactionAsync(async (session, cancellationToken) =>
{
await session.ExecuteAsync(new CommandDefinition(
insertSql,
parameters,
cancellationToken: cancellationToken));
Product inserted = await session.Query<Product>()
.SingleAsync(product => product.Id == productId, cancellationToken);
return inserted;
}, cancellationToken: ct);
A context type can be registered only once. Registering it twice throws immediately, preventing a later registration from silently replacing its database. Contexts and their sets are scoped; do not use a context concurrently or resolve it from the root service provider.
The short IConfiguration overloads bind the conventional Dapper:SqlServer or
Dapper:PostgreSql section. Pass a section name when each typed context has its own configuration:
{
"Dapper": {
"Databases": {
"Catalog": {
"ConnectionString": "Host=localhost;Database=catalog",
"CommandTimeoutSeconds": 30
},
"Reporting": {
"ConnectionString": "Server=localhost;Database=reporting;...",
"CommandTimeoutSeconds": 60
}
}
}
}
builder.Services.AddDapperPostgreSql<CatalogDatabase>(
builder.Configuration,
"Dapper:Databases:Catalog");
builder.Services.AddDapperSqlServer<ReportingDatabase>(
builder.Configuration,
"Dapper:Databases:Reporting");
Connection configuration is bound and validated during service registration. The context model
(OnModelCreating, entity maps, LINQ compilers) is built once per context type on first
resolution, validated, and shared by every scope; only the connection source is per scope.
Mappings can also live in reusable configuration classes and be discovered from an assembly:
public sealed class ProductConfiguration : IDapperEntityConfiguration<Product>
{
public void Configure(DapperEntityMapBuilder<Product> entity)
{
entity.ToTable("products", "catalog");
entity.HasKey(product => product.Id, generatedOnAdd: true);
entity.Property(product => product.Id, "id");
entity.Property(product => product.Name, "product_name");
}
}
public sealed class CatalogDatabase : DapperDbContext
{
public DapperSet<Product> Products => Set<Product>();
protected override void OnModelCreating(DapperModelBuilder model)
=> model.ApplyConfigurationsFromAssembly(
typeof(ProductConfiguration).Assembly);
}
Concrete configuration classes may be non-public but must have a parameterless constructor. A
configuration may implement IDapperEntityConfiguration<TEntity> for more than one entity.
Standard data annotations work without any model-builder registration:
[Table("products", Schema = "catalog")]
public sealed class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("id")]
public long Id { get; set; }
[Column("product_name")]
public string Name { get; set; } = string.Empty;
[NotMapped]
public string DisplayName => $"#{Id}: {Name}";
}
Convention mapping uses public properties, the entity type name as the table, and Id or
{EntityName}Id as the key. [Table], [Column], [Key], [DatabaseGenerated], and [NotMapped]
are honored. Conventions skip properties that cannot be columns: computed get-only properties
(no setter and no backing field) and navigation/collection types (classes other than string,
byte[], Json<T> or types with a registered Dapper handler; collections other than scalar
arrays). Map such a property explicitly with entity.Property(x => x.Prop, "column").
Conventions and attributes are applied first; later fluent or scanned configurations override them.
Custom IQueryable
Inject the concrete application context and write normal LINQ:
using LowCodeHub.Dapper.Abstractions;
using LowCodeHub.Dapper.Querying;
public sealed class ProductReader(CatalogDatabase database)
{
public Task<List<ProductSummary>> ListAsync(CancellationToken ct)
=> database.Query<Product>()
.Where(product => product.IsActive)
.OrderBy(product => product.Name)
.Select(product => new ProductSummary(product.Id, product.Name, product.Price))
.ToListAsync(ct);
}
The query object implements IOrderedQueryable<T> and IAsyncEnumerable<T>. It keeps the root
expression, preserves it through CreateQuery<T> projections, compiles it into parameterized SQL,
then lets Dapper materialize the result. There is no client-evaluation fallback: an unsupported
operator throws NotSupportedException and names the missing translation.
The initial provider supports:
Where,Select, chained projections,OrderBy/ThenBy,Distinct,Skip, andTakeFirst,FirstOrDefault,Single,SingleOrDefault,Count,LongCount, andAnySum,Min,Max, andAveragefor non-paged scalar queries- comparisons (including
char), boolean/null composition, captured parameters, stringContains/StartsWith/EndsWith, arithmetic, coalescing, conditionals,ToLower,ToUpper, andTrim - string concatenation (
a + b,string.Concat) asCONCAT(...), so a null operand behaves as""exactly like C# - local collection membership
ids.Contains(x.Id)(arrays, lists, sets, enums, nullable values) asIN @idson SQL Server (Dapper list expansion) and= ANY(@ids)with a typed array on PostgreSQL; an empty collection becomes1 = 0and anullelement matchesIS NULL - constructor, record, anonymous-type, member-initializer, and scalar projections
- sync LINQ execution plus
ToListAsync,ToArrayAsync,AsAsyncEnumerable,FirstAsync,FirstOrDefaultAsync,SingleAsync,SingleOrDefaultAsync,CountAsync,LongCountAsync, andAnyAsync,SumAsync,MinAsync,MaxAsync, andAverageAsync
Inspect a query without executing it:
DapperQueryPlan plan = query.ToDapperQuery(); // SQL + DynamicParameters
string sql = query.ToQueryString(); // parameterized SQL only
query.ToString() also returns the SQL, and never throws: an untranslatable query returns a
description of the failure instead, so debuggers and loggers stay usable.
EnableQueryPlanCache caches the parse of an expression instance that is executed repeatedly and
interns generated SQL. Translation still runs per new expression tree (captured values can change
the SQL, e.g. null checks and collection sizes), so the cache helps reused query objects most.
This is intentionally not an EF clone. It does not provide tracking, change detection, navigation
Include, or hidden lazy loading. Operators that need multi-source/subquery translation, such as
Join and GroupBy, should use a database stored procedure or function for medium/complex work.
Short, direct, single-purpose SELECT statements may use the raw Dapper layer below.
The compiler first creates a provider-independent query model and then renders dialect SQL.
Applications can register IDapperMethodCallTranslator implementations for explicit semantics
that belong to the application or provider. A translator receives safe child translation,
captured-value parameterization, and the active provider. Translators run before the built-in
translations. Local collections already translate Contains (see above); collections wrapped in
Json<T> have the built-in JSON translations below.
JSON arrays and complex values
Use Json<T> for a value stored or passed as one JSON document. The same wrapper handles
int[], string[], Guid[], lists, arrays of objects, and individual complex objects:
using LowCodeHub.Dapper.Models;
var parameters = new
{
CustomerId = 42,
Name = "Order A",
Ids = Json.From(new[] { 1, 2, 3 }),
Items = Json.From(new[] { new OrderItem(7, 2), new OrderItem(8, 4) })
};
IReadOnlyList<OrderResult> results = await db.QueryStoredProcedureAsync<OrderResult>(
new DapperStoredProcedure("dbo.save_order", parameters), ct);
public sealed record OrderItem(int ProductId, int Quantity);
public sealed class OrderResult
{
public int CustomerId { get; set; }
public string Name { get; set; } = "";
public Json<int[]> Ids { get; set; } = null!;
public Json<OrderItem[]> Items { get; set; } = null!;
}
Read the deserialized array through results[0].Ids.Value. No procedure DTO interface, TSelf,
UDT, or per-type handler registration is required. Entity properties use the same Json<T> type
for repository inserts, updates and materialization. Raw queries, scalar commands, streaming,
sessions and multiple-result callbacks use the same handlers.
AddDapperSqlServer<TContext> and AddDapperPostgreSql<TContext> discover closed Json<T>
properties and fields in the context assembly and loaded assemblies that reference this package.
Typed command results, parameters, entity maps and Json.From also prepare types on first use,
including closed generic DTOs. Discovery is cached and synchronized. This uses reflection and
runtime generic construction; trimmed/Native AOT deployment is not supported by this mechanism.
Assemblies used with direct Dapper calls outside the context should be loaded before registration.
SQL Server parameters are nvarchar(max) with unbounded size; Npgsql parameters are jsonb.
The database signature must accept that representation. The package does not create or alter a
procedure, table, database compatibility level, or UDT. For example, the four-input SQL Server
procedure above can accept and return both arrays directly:
CREATE PROCEDURE dbo.save_order
@CustomerId int,
@Name nvarchar(100),
@Ids nvarchar(max),
@Items nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
-- Use OPENJSON(@Ids) to read primitive elements, or a typed schema for objects:
-- SELECT ProductId, Quantity FROM OPENJSON(@Items)
-- WITH (ProductId int, Quantity int);
SELECT @CustomerId AS CustomerId, @Name AS Name, @Ids AS Ids, @Items AS Items;
END;
For PostgreSQL, declare the collection inputs as jsonb and consume them with
jsonb_array_elements or jsonb_to_recordset. PostgreSQL procedures return values through
OUT/INOUT parameters; use a function called with raw SELECT when the database contract
returns a table. SQL Server JSON querying requires compatibility level 130 or later.
Querying JSON
JSON collections and scalar object members work in the typed LINQ/specification translator:
var orders = await db.Query<Order>()
.Where(order => order.Ids.Value.Contains(7))
.Where(order => order.Items.Value.Any(item => item.Quantity > 2))
.Where(order => order.Settings.Value.Address.City == "Cairo")
.Select(order => new
{
order.Id,
ItemCount = order.Items.Value.Length,
City = order.Settings.Value.Address.City,
Address = Json.From(order.Settings.Value.Address)
})
.ToListAsync(ct);
Supported collection operations are primitive Contains, Any, All, Count, LongCount,
array Length, and collection Count properties. Any, All, Count and LongCount accept
element predicates; object predicates can traverse nested properties and collections. Both
Enumerable and C# 14 array/span Contains forms are recognized. Comparer overloads and object
equality via Contains are rejected. Keep Json<T> in structured projections (or use Json.From
for a nested object/collection); projecting a whole bare complex .Value would bypass decoding
and is rejected. Individual scalar members can be projected normally.
JSON serialization uses JsonSerializerOptions.Default (case-sensitive property names, numeric
enums) unless options.JsonSerializerOptions is set. Dapper type handlers are process-wide, so
every context must pass the same instance (a different instance fails registration); it becomes
read-only once registered. JsonPropertyName and the configured PropertyNamingPolicy are honored
by serialization and query paths. Custom converters (attributes or Converters in the options,
e.g. JsonStringEnumConverter) remain usable for storage and reading, but querying the shapes they
produce requires raw SQL and is rejected by the translator. PostgreSQL reads JSON DateTime
members as timestamptz, so values written with a Z/offset compare correctly. Dictionary/indexer traversal, collection indexing, JSON mutation functions,
and SelectMany are also raw-SQL operations. SQL Server decimal member extraction uses
decimal(38,18); use explicit SQL when another precision/scale is needed. String matching uses
the database collation. SQL Server scalar string extraction supports values longer than 4,000
characters. A wrapped byte[] follows System.Text.Json's base64-string format, so it is not a
queryable JSON array.
A null wrapper represents SQL NULL; Json.From<T?>(null) represents JSON null; an empty array
represents []. These round-trip distinctly. Missing/null scalar paths yield SQL NULL, and
nullable comparisons use two-valued boolean semantics. Missing, SQL-null and JSON-null
collections behave as empty collections in queries: Any is false, All is true, and counts
are zero. Stored documents should match their declared CLR shape; malformed documents or
incompatible scalar values fail instead of being silently repaired.
JSON output parameters
Use the extensions on Dapper's existing DynamicParameters:
var parameters = new DynamicParameters();
parameters.Add("CustomerId", 42);
parameters.AddJson("Ids", new[] { 1, 2, 3 });
parameters.AddJsonOutput("Result");
parameters.AddJson("State", currentState, ParameterDirection.InputOutput);
await db.ExecuteStoredProcedureAsync(new DapperStoredProcedure("process_order", parameters), ct);
OrderSummary? result = parameters.GetJson<OrderSummary>("Result");
AddJson accepts an unwrapped value and treats a null input as SQL NULL. AddJsonOutput and
input/output parameters receive the correct provider type and SQL Server size automatically.
GetJson<T> returns the unwrapped T, including default(T) for SQL NULL. A JSON null requires
a reference or nullable T, following System.Text.Json's rules; use a nullable scalar type when
distinguishing null from the default value matters. It also decodes
ordinary JSON string output parameters. Read outputs after the command completes and any
result reader has been consumed/disposed. Dapper's ordinary Get<T> performs a cast and does
not deserialize JSON. Like ordinary DynamicParameters, a parameter bag is not for concurrent
command execution. Scalar return codes remain ordinary Dapper parameters.
User-registered parameter types
Bare arrays retain Dapper's SQL Server IN @Ids expansion and Npgsql's native array handling.
Wrapping a value in Json.From is the explicit choice to send JSON. Do not register a global
JSON handler for bare int[], string[], or Guid[]: that would replace their native behavior.
In raw SQL, Npgsql supports array inputs without a custom handler:
IReadOnlyList<Product> rows = await db.QueryAsync<Product>(new CommandDefinition(
"SELECT * FROM catalog.products WHERE id = ANY(@Ids)",
new { Ids = new[] { 3, 8, 13 } },
cancellationToken: ct));
options.AddTypeHandler(new MyDomainIdHandler()) remains available for domain IDs, ranges,
spatial types, or another SqlMapper.TypeHandler<T>. AddTypeHandler(Type, ITypeHandler) supports
runtime-selected types. Configured handlers are installed during database registration. Like
SqlMapper.AddTypeHandler, registrations are process-wide: use stateless provider-aware handlers,
and do not configure different serializers for the same CLR type in different contexts. The built-in
Json<T> handlers use the one process-wide JsonSerializerOptions on both providers.
Dapper ICustomQueryParameter, DbString, dynamic parameters, output parameters, stored
procedures, and provider-specific values can also be supplied through the raw APIs or an owned
session connection.
Stored procedures
Stored procedures are first-class on both the concrete context and IDapperSession:
var parameters = new DynamicParameters();
parameters.Add("Id", productId);
parameters.Add("Affected", dbType: DbType.Int32, direction: ParameterDirection.Output);
await db.ExecuteStoredProcedureAsync(
new DapperStoredProcedure("catalog.activate_product", parameters), ct);
int affected = parameters.Get<int>("Affected");
ExecuteStoredProcedureAsync, QueryStoredProcedureAsync<T>,
ExecuteStoredProcedureScalarAsync<T>, and QueryStoredProcedureMultipleAsync<T> preserve Dapper
dynamic/custom parameters, output and return values, flags, timeout, cancellation, result grids,
and the current session transaction. Procedure naming and behavior remain provider-specific;
PostgreSQL functions invoked through SELECT should use the raw query APIs.
Raw Dapper, streaming, and multiple results
CommandDefinition is the command currency, so timeout, command type, flags, cancellation,
DynamicParameters, and callbacks are retained.
The concrete context and session raw command methods take only the CommandDefinition; place the
cancellation token in that definition once.
var result = await db.QueryMultipleAsync(
new CommandDefinition("select count(*) from products; select * from products limit 10", cancellationToken: ct),
async (grid, _) =>
{
int count = await grid.ReadSingleAsync<int>();
List<Product> products = (await grid.ReadAsync<Product>()).AsList();
return new ProductPage(count, products);
});
The callback is deliberate: Dapper's GridReader owns the live reader/command until all grids have
been consumed. The context disposes it and its connection only after the callback finishes.
Unbuffered queries keep their connection alive for the whole async enumeration:
await foreach (Product product in db.QueryUnbufferedAsync<Product>(sql, parameters, cancellationToken: ct))
{
await HandleAsync(product, ct);
}
For multi-mapping, bulk extensions, prepared/provider commands, or any other Dapper API, use the owned connection directly:
Order order = await db.WithConnectionAsync(async (connection, token) =>
(await connection.QueryAsync<Order, Customer, Order>(
sql,
(order, customer) => { order.Customer = customer; return order; },
splitOn: "customer_id"))
.Single(), ct);
Transactions and sessions
await db.InTransactionAsync(async (session, token) =>
{
await session.ExecuteAsync(new CommandDefinition(
insertSql,
product,
cancellationToken: token));
// Generated LINQ uses this same connection and active transaction.
Product inserted = await session.Query<Product>()
.SingleAsync(item => item.ExternalId == product.ExternalId, token);
// The real connection and transaction are available for every Dapper extension.
await session.Connection.ExecuteAsync(updateSql, parameters, session.Transaction);
return product.Id;
}, cancellationToken: ct);
The helper commits after the callback succeeds and rolls back on failure. OpenSessionAsync is
available when transaction boundaries or connection lifetime must be controlled explicitly.
Diagnostics and production behavior
Generated LINQ, repository operations, raw commands, multiple grids, stored procedures, and streams emit activities from
LowCodeHub.Dapper and metrics from the meter with the same name
(lowcodehub.dapper.command.duration, .command.failures, .command.slow,
lowcodehub.dapper.interceptor.failures). SQL text is excluded from activities by default; opt in
with IncludeCommandTextInDiagnostics = true. Configure SlowQueryThreshold to mark slow commands.
Register application hooks with AddDapperInterceptor<TInterceptor>() (scoped). Interceptors see
command metadata but not parameter values. An exception from CommandExecutingAsync cancels the
command. Exceptions from CommandExecutedAsync/CommandFailedAsync are logged (when an
ILogger is registered) and counted, but never change the outcome: a committed write is never
reported as a failure, so callers do not retry it. CommandFailedAsync and stream completion
receive CancellationToken.None.
Each context registers a readiness health check dapper-{ContextTypeName} that opens a connection
through the configured source and runs SELECT 1; disable it with RegisterHealthCheck = false.
The package does not automatically retry commands. Retrying streaming operations or commands
inside a transaction can duplicate work, so resilience policy remains explicit at the application
boundary. Direct DbConnection access remains available for provider bulk APIs and other Dapper
extensions.
Assembly mapping scans use reflection and are marked RequiresUnreferencedCode. Automatic JSON
handler discovery also requires reflection and runtime generic construction. The package does
not promise trimmed/Native AOT support.
LINQ support boundary
| Area | Supported | Preferred boundary |
|---|---|---|
| Single-table filtering/projection | Where, Select, strings, arithmetic, nulls |
Short provider-specific reads may use raw SQL |
| Ordering/paging | OrderBy, ThenBy, Skip, Take, Distinct |
Stored procedure/function for windows or complex paging |
| Terminals/aggregates | First/single/count/any and numeric aggregates, sync/async | Stored procedure/function for complex aggregates |
| JSON | Scalar member paths, collection membership/quantifiers/counts, typed JSON results | Raw SQL for dictionary/indexer traversal, custom converter shapes, complex equality or JSON mutations |
| Relational composition | — | Stored procedure/function for Join, GroupBy, unions, subqueries, CTEs |
| ORM behavior | — | Tracking, Include, lazy loading, and migrations are not provided |
Unsupported expressions fail with NotSupportedException; there is no client-evaluation fallback.
Context sets and specifications
DapperSet<TEntity> provides entity CRUD, typed specifications, paging, queued inserts with
SaveChangesAsync, generated keys, and set-based updates/deletes without exposing repository
interfaces in application constructors. DapperSpecification builders use the same expression
translator and registered application translators as Query<TEntity>().
Use set.Add(entity) and set.AddRange(entities) directly when no insert specification is needed.
SaveChangesAsync flushes only that set's queued inserts in one transaction. It is not a
context-wide change tracker or unit of work: updates/deletes execute immediately, and changes to
previously read objects are not tracked. [DatabaseGenerated(DatabaseGeneratedOption.None)]
preserves application-assigned conventional integer keys.
To insert a large list immediately, without queueing, use InsertRangeAsync:
db.Products.AddRange(products);
await db.Products.SaveChangesAsync(ct); // queued inserts, batched
await db.Products.InsertRangeAsync(rows, ct); // immediate, batched, independent of the queue
Both batch rows into multi-row commands of at most MaxBatchSize rows (default 1000), further
bounded by the provider: SQL Server sends at most 2098 parameters and 1000 rows per command,
PostgreSQL at most 65535 parameters. Every command still runs through interceptors, metrics and
traces (operation repository_insert). All commands share one transaction — the session's, or
one owned by the call — so a failure in any batch writes nothing, leaves SaveChangesAsync's
queue intact and assigns no keys. Generated keys are assigned only after commit (or, with a
session, after the last batch), and are mapped back to their entities by row ordinal:
| Provider | Generated key | No generated key |
|---|---|---|
| SQL Server | MERGE ... USING (VALUES (0, ...), (1, ...)) ON 1 = 0 ... OUTPUT source.ordinal, INSERTED.key INTO @table — OUTPUT order is not guaranteed, the ordinal is; INTO keeps tables with triggers working |
INSERT ... VALUES (...), (...) |
| PostgreSQL | one INSERT ... RETURNING <ordinal>, key per row in a single command (one round trip) — multi-row RETURNING order is not documented |
INSERT ... VALUES (...), (...) |
Values are bound like Dapper binds entity members: type handlers (including Json<T>) apply,
enums are sent as their underlying number, and nulls keep the member's type. For bulk loads of
millions of rows, use the provider's bulk API (SqlBulkCopy, Npgsql binary COPY) on a session
connection.
To combine set writes with other commands in one transaction, pass the session:
await db.InTransactionAsync(async (session, ct) =>
{
db.Products.Add(product);
await db.Products.SaveChangesAsync(session, ct); // enlists in session.Transaction
await db.Products.UpdateAsync(filter, update, session, ct);
await db.Products.RemoveAsync(obsolete, session, ct);
return product.Id;
}, cancellationToken: ct);
Specification details: scalar aggregates (Count, Sum, Average, ...) ignore OrderBy;
Average over integral columns is computed in floating point on both providers (matching LINQ);
a Distinct() projection may only order by projected members, which are emitted by alias.
Raw DapperQueryDefinition/DapperUpdateDefinition fragments are trusted application SQL, not
a security boundary: never concatenate user input into them, use parameters. The only check is a
lint that rejects ; outside quoted text to stop accidental multi-statement fragments.
Numeric casts that safely widen a value are emitted as provider SQL casts, so (double)x.A / x.B
uses floating-point division. Narrowing casts with different rounding/overflow rules across
providers fail with NotSupportedException. Numeric precision and ordering still follow the
database's types and collation. DISTINCT projections can order by their projected members; use
raw SQL when the required ordering needs an additional subquery.
Database-context and repository interfaces are implementation details. Application code must
derive and inject one concrete typed context and access repository behavior through its named
DapperSet<TEntity> properties.
Provider verification
The test suite contains SQL Server and PostgreSQL Testcontainers coverage for LINQ, custom types,
transactions, multiple results, data sources, stored procedures and batched inserts (key mapping
across chunk boundaries, identity/uuid/sequence keys, triggers, rollback). Set
LOWCODEHUB_DAPPER_INTEGRATION_TESTS=1 when Docker is available; otherwise those tests are reported
as skipped. SQLite tests always run for fast execution and semantic coverage.
$env:LOWCODEHUB_DAPPER_INTEGRATION_TESTS = '1'
dotnet test test/LowCodeHub.Dapper.Tests/LowCodeHub.Dapper.Tests.csproj -c Release
Version 0.0.4 added typed JSON values, automatic handler discovery, JSON outputs and JSON LINQ
operations. Version 0.0.5 adds batched inserts (InsertRangeAsync, MaxBatchSize), local-collection Contains, char comparisons, null-safe string concatenation,
session-enlisted set writes, set.Query(), a connection-string overload, ANSI string parameters,
configurable JSON serializer options and a health check. Entity maps, query contexts and LINQ
compilers are now cached per context type instead of rebuilt per scope. It also fixes numeric cast translation, negated nullable comparisons, connection
cleanup after interceptor failures, conventional non-generated keys, scalar projection counts,
DISTINCT paging/order SQL, ordered zero-row counts and raw-command cancellation propagation.
AI agent skills
This package targets net11.0 and includes version-matched agent instructions under
skills/. After restoring your application's dependencies, install them into your
agent's skill directory:
dotnet tool install --global dotnet-package-skills --prerelease
dotnet-package-skills install
The default destination is .agents/skills/. For Claude, pass
--destination .claude/skills. Run the installer again after package upgrades.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Dapper (>= 2.1.89)
- Microsoft.Data.SqlClient (>= 7.1.2)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 11.0.0)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 11.0.0)
- Npgsql (>= 10.0.3)
- System.Security.Cryptography.Pkcs (>= 11.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.