Persistence with Dapper & PostgreSQL UNNEST
Per ADR-002, write-heavy and latency-sensitive persistence paths favor explicit raw SQL over Dapper using EricksonLopez.DapperExtensions and EricksonLopez.DapperExtensions.PostgreSql rather than opaque ORM change tracking.
- Predictable execution plans: Queries are written explicitly in SQL with exact indexes and parameter types, eliminating unexpected N+1 queries or client-side evaluation.
- Single-roundtrip batching with
UNNEST: PostgreSQL array parameters (UNNEST(@Ids, @Skus, @Quantities)) allow inserting or updating thousands of rows in a single parameterized statement without dynamic SQL string concatenation. - Trimming and Native AOT discipline:
EricksonLopez.DapperExtensionsprovidesAotMultiMapReader, explicitIDataReaderMapper<T>, and theNoDynamicDapperAnalyzerto forbid untypeddynamicrow mapping.
EricksonLopez.DapperExtensions.PostgreSql (2.0.0, which supersedes the deprecated dapper-extensions-pg repository) supplies BulkExtensions, PagedQueryExtensions, TransactionExtensions, NpgsqlTypeHandlerRegistrar, and SqlResilienceDefaults.ForPostgreSqlPipeline():
using System;using System.Collections.Generic;using System.Data;using System.Threading;using System.Threading.Tasks;using Dapper;
namespace Example.Infrastructure.Persistence;
public sealed record LedgerLineRow(Guid Id, string AccountCode, decimal Amount);
public static class LedgerBatchWriter{ public static async Task<int> InsertLinesAsync( IDbConnection connection, IDbTransaction transaction, IReadOnlyList<LedgerLineRow> rows, CancellationToken cancellationToken) { if (rows.Count == 0) { return 0; }
var ids = new Guid[rows.Count]; var codes = new string[rows.Count]; var amounts = new decimal[rows.Count];
for (int i = 0; i < rows.Count; i++) { ids[i] = rows[i].Id; codes[i] = rows[i].AccountCode; amounts[i] = rows[i].Amount; }
const string sql = """ INSERT INTO ledger_lines (id, account_code, amount) SELECT u.id, u.account_code, u.amount FROM UNNEST(@Ids, @Codes, @Amounts) AS u(id, account_code, amount); """;
var command = new CommandDefinition( sql, new { Ids = ids, Codes = codes, Amounts = amounts }, transaction: transaction, cancellationToken: cancellationToken);
return await connection.ExecuteAsync(command); }}For large tables, combine EricksonLopez.Specification.PostgreSql or EricksonLopez.Pagination keyset cursors (SeekAfter / SeekBefore) with indexed (created_at, id) tuples to maintain constant-time seeking regardless of page depth.