Rochas.DapperRepository 1.9.3

dotnet add package Rochas.DapperRepository --version 1.9.3
                    
NuGet\Install-Package Rochas.DapperRepository -Version 1.9.3
                    
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="Rochas.DapperRepository" Version="1.9.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Rochas.DapperRepository" Version="1.9.3" />
                    
Directory.Packages.props
<PackageReference Include="Rochas.DapperRepository" />
                    
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 Rochas.DapperRepository --version 1.9.3
                    
#r "nuget: Rochas.DapperRepository, 1.9.3"
                    
#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 Rochas.DapperRepository@1.9.3
                    
#: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=Rochas.DapperRepository&version=1.9.3
                    
Install as a Cake Addin
#tool nuget:?package=Rochas.DapperRepository&version=1.9.3
                    
Install as a Cake Tool

README - DapperRepository

Repositório genérico para acesso a dados usando Dapper, com foco em simplicidade, performance e baixo acoplamento.
Segue o padrão de Repositório e Unidade de Trabalho descritos por Martin Fowler, sem impor novas linguagens, controle de estado ou proxies dinâmicos.

Este componente foi desenhado para uso direto com POCOs decorados com metadados que orientam a consulta, persistência e relacionamento entre entidades.


📌 Instalação

dotnet add package Rochas.DapperRepository

📌 Nome da Interface

IGenericRepository<T>

📌 Exemplo de uso típico — Instância manual:

var connString = "Data Source=sample.db;Cache=Shared";

using var repo = new GenericRepository<SampleEntity>(DatabaseEngine.SQLite, connString);

var result = repo.Search('Celulares');

📌 Exemplo de Registro no DI

services.AddScoped<IGenericRepository<SampleEntity>>(provider =>
    new GenericRepository<SampleEntity>(
        DatabaseEngine.SQLite,
        configuration.GetConnectionString("Default")));

Implementação em serviço de domínio:

private readonly IGenericRepository<SampleEntity> _repo;

    public SampleService(IGenericRepository<SampleEntity> repo)
    {
        _repo = repo;
    }

📌 Exemplo de Entidade (Anotações de Metadados)

Usando PascalCase (convencional)

[Table] e [Column] são opcionais. Quando omitidos, o componente usa o nome da classe para a tabela e o nome da propriedade para a coluna (PascalCase):

[Cacheable]
public class SampleEntity
{
    [Key]
    [AutoGenerated]
    public int Id { get; set; }

    [RangeFilter(LinkedRangeProperty = "CreationDateEnd")] 
    public DateTime CreationDate { get; set; } 
    
    [NotMapped] 
    public DateTime CreationDateEnd { get; set; }

    [Filterable]
    public string Name { get; set; }

    public int Age { get; set; }

    public bool Active { get; set; }

    [RelatedEntity(Cardinality = RelationCardinality.OneToMany, 
                   ForeignKeyAttribute = "ParentId")]
    public IList<ChildEntity> Childs { get; set; }
}

public class ChildEntity
{
    [Key]
    public int Id { get; set; }

    public int ParentId { get; set; }

    public string Description { get; set; }
}

Usando nomes customizados

Quando necessário (ex.: banco com nomes snake_case ou colunas com nomes diferentes das propriedades), use [Table] e [Column]:

[Table("sample_entities")]
public class SampleEntity
{
    [Key]
    [AutoGenerated]
    public int Id { get; set; }

    [Column("creation_date")]
    public DateTime CreationDate { get; set; }

    [Column("name")]
    public string Name { get; set; }
}

Regra: Se [Table] não existir, usa o nome da classe. Se [Column] não existir, usa o nome da propriedade.

🔧 Métodos CRUD disponíveis no repositório

➕ Add (inclusão de entidade no repositório)

var entity = new SampleEntity
{
    Name = "Renato Rocha",
    Email = "rrocha@example.com"
};

repo.Add(entity);

➕ AddRange (inclusão de múltiplas entidades no repositório)

var list = new List<SampleEntity>() { 
                new SampleEntity() {
                    Name = "Renato Rocha",
                    Resume = "Software Architect"
                },
                new SampleEntity() {
                    Name = "Roberto Dias",
                    Resume = "Infra DevOps"
                },
            };

repo.AddRange(list);

✏️ Update (atualização de entidade do repositório)

var filter = new SampleEntity { DocNumber = 12345 };
var entityToUpdate = await repo.Get(filter);
entityToUpdate.Age = 40;

int affected = await repo.Update(entityToUpdate, filter);

❌ Remove (remoção de entidade do repositório)

var filterToRemove = new SampleEntity { DocNumber = 12345 };

int removed = await repo.Remove(filterToRemove);

🔍 Query (consultas por filtro tipado)

var all = await repo.Query(new SampleEntity()); //Listar todos

var filter = new SampleEntity { Name = "Roberto", Email = "gmail.com" };
var results = await repository.Query(filter, recordsLimit:10);

Utilize o parâmetro booleano filterConjunction para definir o comportamento dos atributos na consulta, conjunção lógica E (ligado), disjunção lógica OU (desligado).

Quando a conjunção é utilizada o critério aplicado é de igualdade, do contrário semelhança.


🔍 Query (consultas por intervalo [RangeFilter])

var filter = new SampleEntity
{
    CreatedAtStart = new DateTime(2024, 01, 01),
    CreatedAtEnd   = new DateTime(2024, 12, 31)
};

var results = await repository.Query(filter);

Somente atributos marcados com [RangeFilter] e referência ao atributo auxiliar.


🔎 Search (buscas usando [Filterable])

var results = await repository.Search("Rua Bruchelas");

Somente atributos marcados com [Filterable] entram automaticamente na busca.


📄 Search (paginação direta)

var result = await repository.Search("Paulo", page: 1, pageSize: 20);

PaginatedResult<T>

public class PaginatedResult<T>
{
    public IReadOnlyList<T> Items { get; set; }
    public int TotalCount { get; set; }
    public int Page { get; set; }
    public int PageSize { get; set; }
    public int PageCount => PageSize > 0 ? (int)Math.Ceiling((double)TotalCount / PageSize) : 0;
}

📄 Query (paginação direta)

var filter = new SampleEntity { Active = true };

// Assíncrono
var result = await repository.Query(filter, page: 1, pageSize: 10);

// Síncrono
var result = repository.QuerySync(filter, page: 1, pageSize: 10);

foreach (var item in result.Items)
{
    Console.WriteLine($"{item.Name} - Age: {item.Age}");
}

Via Builder

var result = await repository.Query(filter)
    .OrderBy(["Name"])
    .Paginate(1, 10);

var result = repository.QuerySync(filter)
    .OrderBy(["Name"])
    .Paginate(1, 10);

🔗 Leitura automática da composição usando [RelatedEntity]

repos.Query(filterEntity, loadComposition: true);

Configuração de relacionamentos ( 1-1 , 1->N , N<-1 , N<->N ):

[RelatedEntity(Cardinality = RelationCardinality.OneToOne, 
               ForeignKeyAttribute = "ParentId")] 
public <ChildEntity> Child { get; set; }

[RelatedEntity(Cardinality = RelationCardinality.OneToMany, 
               ForeignKeyAttribute = "ParentId")] 
public IList<ChildEntity> Childs { get; set; }

🧱 Query — consultas fluentes com OrderBy/GroupBy

O componente oferece uma API fluente (builder pattern) para montagem de consultas com ordenação e agrupamento. O builder é awaitable: a execução acontece quando o resultado é aguardado (await).

Entry points

// Retorna IQueryBuilder — consulta simples ou com encadeamento
var builder = repos.Query(filter);

// Ordenação e agrupamento direto no repositório
var result = await repos.OrderBy(["Name"]);
var result = await repos.OrderByDescending(["Name"]);
var result = await repos.GroupBy(["Category"]);

Consulta simples (sem ordenação/agrupamento)

var all = await repos.Query(new SampleEntity());   // await executa
var list = repos.QuerySync(filter).ToList();       // builder síncrono

Ordenação com params string[]

// Ascendente (padrão)
var result = await repos.Query(filter).OrderBy(["Name"]);

// Descendente
var result = await repos.Query(filter).OrderByDescending(["Name"]);

// Múltiplas colunas
var result = await repos.Query(filter).OrderBy(["Age", "Name"]);
var result = await repos.Query(filter).OrderByDescending(["Category", "Name"]);

Agrupamento (GROUP BY)

// Agrupamento simples por colunas
var result = await repos.Query(filter).GroupBy(["Category"]);

// Agrupamento com agregações (SUM, COUNT, MIN, MAX, AVG)
var agg = new Dictionary<string, DataAggregationType>
{
    { "Price", DataAggregationType.Sum },
    { "Price", DataAggregationType.Average }
};
var result = await repos.Query(filter).GroupBy(["Category"], agg);

Nota: para agregar valores (SUM, COUNT, MIN, MAX, AVG) utilize Dictionary<string, DataAggregationType> como segundo parâmetro do GroupBy. O componente gera SELECT ... GROUP BY ... automaticamente.

Encadeamento (qualquer ordem)

var result = await repos.Query(filter)
    .GroupBy(["Category"])
    .OrderByDescending(["Price"]);

var result = repos.QuerySync(filter)
    .GroupBy(["Category"])
    .OrderBy(["Name"])
    .ToList();

A ordem dos métodos não importa: o builder coleta os atributos de ordenação e agrupamento e a execução monta o SQL na ordem correta (SELECT → FROM → WHERE → GROUP BY → ORDER BY).


🗄️ Consultas Fato DW/ETL — [RelationalColumn] e [DataAggregationColumn]

Para trabalhos de Data Warehouse e ETL, o componente oferece um modo alternativo de montagem de entidades fato com queries baseadas em anotações:

  • [RelationalColumn] — colunas de tabelas dimensionais com geração automática de JOIN (INNER/LEFT)
  • [DataAggregationColumn] — colunas calculadas com funções de agregação (SUM, COUNT, MIN, MAX, AVG) e respectivo tipo em DataAggregationType

Exemplo de entidade fato

[Table("fact_sales")]
public class FactSalesEntity
{
    [Key] [AutoGenerated]
    public int Id { get; set; }

    [Column("product_id")]
    public int ProductId { get; set; }

    [Column("total_amount")]
    public decimal TotalAmount { get; set; }

    // JOIN automático: dim_product.product_name AS ProductName
    // KeyColumn = coluna na tabela fato | ForeignKeyColumn = coluna na dim
    [RelationalColumn(
        TableName = "dim_product",
        ColumnName = "product_name",
        ColumnAlias = "ProductName",
        KeyColumn = "product_id",
        ForeignKeyColumn = "id",
        JunctionType = RelationalJunctionType.Mandatory)]
    public string ProductName { get; set; }

    // Agregação: SUM(fact_sales.total_amount) AS SumTotalAmount
    [DataAggregationColumn(ColumnName = "total_amount", AggregationType = DataAggregationType.Sum)]
    public decimal SumTotalAmount { get; set; }

    // Agregação: COUNT(fact_sales.id) AS CountSales
    [DataAggregationColumn(ColumnName = "id", AggregationType = DataAggregationType.Count)]
    public int CountSales { get; set; }
}

SQL gerado automaticamente

SELECT dim_product.product_name AS ProductName,
       SUM(fact_sales.total_amount) AS SumTotalAmount,
       COUNT(fact_sales.id) AS CountSales,
       fact_sales.id, fact_sales.product_id, fact_sales.total_amount
FROM fact_sales
INNER JOIN dim_product ON fact_sales.product_id = dim_product.id
WHERE 1 = 1

Consultando

// Consulta simples com JOINs e agregações automáticas
var result = await repos.Query(new FactSalesEntity());

// Com ordenação por coluna relacional
var result = await repos.Query(new FactSalesEntity())
    .OrderBy(new[] { "ProductName" });

// Com agrupamento
var result = await repos.Query(new FactSalesEntity())
    .GroupBy(new[] { "ProductId" });

Tipos de junção (RelationalJunctionType)

Tipo SQL gerado Uso
Mandatory INNER JOIN Somente registros que casam
Optional LEFT JOIN Inclui registros sem correspondência

Tipos de agregação (DataAggregationType)

Tipo Função SQL
Sum SUM(col) AS Alias
Count COUNT(col) AS Alias
Minimum MIN(col) AS Alias
Maximum MAX(col) AS Alias
Average AVG(col) AS Alias

Nota: propriedades marcadas com [RelationalColumn] ou [DataAggregationColumn] são ignoradas em operações de INSERT/UPDATE — elas existem apenas para consulta (leitura).


⚡ Cache Plugável (ICacheProvider)

O componente oferece provedores de cache intercambiáveis via ICacheProvider. O comportamento padrão permanece in-memory (InMemoryCacheProvider), mas é possível injetar Redis, Garnet ou canais de replicação sem alterar o código do repositório.

Ativando o cache na entidade

[Cacheable]
[Table("sample_entities")]
public class SampleEntity { ... }

É possível ligar/desligar o cache no construtor:

var repos = new GenericRepository<SampleEntity>(DatabaseEngine.SQLite, connString, useCache: true);

InMemoryCacheProvider (padrão)

DataCache.Initialize(memorySizeLimit: 100); // MB
DataCache.Initialize();                      // sem limite

DistributedCacheProvider (Redis / Garnet)

Placeholder para implementação com Microsoft.Extensions.Caching.StackExchangeRedis ou Microsoft.Garnet (Redis-compatible in-memory da Microsoft).

DataCache.Initialize(new DistributedCacheProvider("localhost:6379"));

CompositeCacheProvider (L1 InMemory + L2 Distribuído)

Para alta disponibilidade com múltiplas instâncias:

DataCache.Initialize(new CompositeCacheProvider(
    new InMemoryCacheProvider(),
    new DistributedCacheProvider("redis:6379")));

L1 local (microssegundos) → L2 compartilhado entre pods (milissegundos) → banco SQL.

PersistenceChannelCacheProvider (Replicação Master→Slave)

Canal de persistência assíncrona para clusters SQL master-slave. O master publica no canal; múltiplos consumidores (slaves) persistem nos seus bancos.

// Master
var localCache = new InMemoryCacheProvider();
var channel = new PersistenceChannelCacheProvider(localCache);
DataCache.Initialize(channel);

// Slave (consumer)
await foreach (var msg in channel.ConsumeAsync(ct))
{
    switch (msg.Action)
    {
        case ChannelAction.Put:
            slaveRepo.AddSync(msg.CacheItem);
            break;
        case ChannelAction.Del:
            slaveRepo.RemoveSync(msg.CacheKey);
            break;
    }
}

Backpressure: BoundedChannelFullMode.Wait — não perde mensagens se o canal lotar.


📊 Benchmark — DapperRepository vs EF Core

Windows 11, Intel i5-7500T, .NET 9.0, SQLite, 5.000 linhas

Cenário EF Core DapperRepository Vitória
InsertIndividual 3.2 ms 3.1 ms ORM 1.1x
BulkInsert_100 32.8 ms 33.5 ms Empate
GetById 526 μs 409 μs ORM 1.3x
Update_Individual 2.9 ms 2.7 ms ORM 1.1x
Delete_Individual 3.2 ms 3.5 ms Empate
CountSync 508 μs 536 μs Empate
Search_Filterable 1.0 ms 1.2 ms Empate
Sort_5000_rows_ORDER_BY 61.6 ms 38.6 ms ORM 1.6x
Sort_MultiColumn 61 ms 41 ms ORM 1.5x
GroupBy_Simple 7.3 ms 1.0 ms ORM 7.3x
GroupBy_AggAll 3.1 ms 1.0 ms ORM 3.1x
GroupBy_Having 2.5 ms 1.1 ms ORM 2.3x
QueryRaw_Select 3.5 ms 3.2 ms ORM 1.1x
SearchPaginated 2.5 ms 3.1 ms Empate*
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.9.3 77 8/11/2026
1.7.5 84 8/10/2026
1.6.8 75 8/9/2026
1.6.3 90 8/9/2026
1.6.2 81 8/9/2026
1.6.0 91 8/8/2026
1.4.0 82 8/7/2026
1.3.0 440 11/30/2025
1.2.8 417 6/1/2025
1.2.7 561 3/13/2025
Loading failed

v1.9.3 - [FIX] IDbConnection constructor infers engine from connection type instead of defaulting to PostgreSQL. [FIX] Guid PK [AutoGenerated] included in INSERT. [NEW] [Filterable] on string[] for Search LIKE. [NEW] Primitive arrays as CSV TEXT; byte[] as base64 TEXT. v1.9.0 - [FIX] SQLite driver to Microsoft.Data.Sqlite 9.0.18. [FIX] Multi-JOIN space separator (invalid SQL). [FIX] .NET 9 deps (System.Text.Json 9.0.18, Microsoft.Data.SqlClient 6.1.1, Npgsql 8.0.9) removes MSB3277/Channels. [TEST] Tests to net9.0, Mode=ReadWriteCreate; 128/128 passing, 0 warnings. [FIX] PostgreSQL: DateTime/DateTimeOffset equality instead of LIKE; boolean ANSI TRUE/FALSE (PG/MySQL/SQLite) and =1/=0 (SQLServer); numeric excluded from LIKE; StartTransaction reuses active; removed PG ToLower() from EntityReflector; QuoteIdentifier double-quotes PG names; BooleanLiteral engine-aware; GetLastIdSql engine-specific (lastval/LAST_INSERT_ID/last_insert_rowid/@@IDENTITY); removed dead ParseOrdinationAttributes(Dictionary). v1.8.8 - [NEW] Engine auto-detection from connection string (PG, MySQL, SQLServer, SQLite). [FIX] SetParentChildEntity null/no-setter child guard; self-referencing ManyToOne (ParentId) composition without overflow. v1.8.6 - Builder Pattern & ORM Hardening: [NEW] IQueryBuilder/IQuerySyncBuilder/IQueryPaginatedBuilder fluent API; GuidStringHandler EnsureRegistered; enum serialized as int. [FIX] FillComposition cycle detection (type+PK); OneToMany null guard; Dispose tx-before-connection; tx Dispose prevents locks; disconnect with dispose; PersistComposition disconnects after commit; recursion support; ParseComposition ReadOnlyCollection; enum to int. [FIX] BaseEntity default constructor sets CreatedAt. [PERF] EntityPropsCache; ColumnMappingCache; SQL dump DEBUG only.