Rochas.DapperRepository 1.7.5

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


📄 SearchPaginated (buscas paginadas com [Filterable])

Retorna PaginatedResult<T> com items, contagem total e metadados de paginação.

var result = await repository.SearchPaginated(
    criteria: "Paulo",
    page: 1,
    pageSize: 20,
    sortAttributes: "Name",
    orderDescending: false
);

Console.WriteLine($"Total: {result.TotalCount}");
Console.WriteLine($"Página {result.Page} de {result.PageCount}");

foreach (var item in result.Items)
{
    Console.WriteLine(item.Name);
}

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;
}

📄 QueryPaginated (consultas paginadas por filtro tipado)

var filter = new SampleEntity { Active = true };

var result = await repository.QueryPaginated(
    filter,
    page: 1,
    pageSize: 10,
    sortAttributes: "Name",
    orderDescending: true,
    filterConjunction: true
);

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

Sincrono

var result = repository.SearchPaginatedSync("termo", page: 1, pageSize: 10);
var result = repository.QueryPaginatedSync(filter, page: 1, pageSize: 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) ou materializado com .ToList()/.ToListAsync().

Entry points

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

// Retorna IQueryPaginatedBuilder — consulta paginada
var pagedBuilder = repos.QueryPaginated(filter);

Consulta simples (sem ordenação/agrupamento)

var all = await repos.Query(new SampleEntity());   // await executa
var list = repos.Query(filter).ToList();           // materializa sync
var listAsync = await repos.Query(filter).ToListAsync();

Ordenação

// Ascendente (padrão) — sempre array de strings
var result = await repos.Query(filter).OrderBy(new[] { "Name" });

// Descendente
var result = await repos.Query(filter).OrderBy(new[] { "Name" }).Descending();
var result = await repos.Query(filter).OrderBy(new[] { "Name" }, descending: true);

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

Agrupamento (GROUP BY — DW/ETL)

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

// Agrupamento por múltiplas colunas
var result = await repos.Query(filter).GroupBy(new[] { "Category", "Status" });

Nota: para agregar valores (SUM, COUNT, MIN, MAX, AVG) utilize as anotações [DataAggregationColumn] nas propriedades da entidade fato (ver seção de consultas DW/ETL abaixo). O GroupBy em conjunto com agregações gera SELECT ... GROUP BY ... automaticamente.

Encadeamento (qualquer ordem)

var result = await repos.Query(filter)
    .GroupBy(new[] { "Category" })
    .OrderBy(new[] { "Category" });

var result = await repos.Query(filter)
    .OrderBy(new[] { "Category" })
    .GroupBy(new[] { "Category" });

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).


📄 QueryPaginated — consultas paginadas fluentes

Uso

// Assíncrono
var result = await repos.QueryPaginated(filter).PaginateAsync(1, 10);

// Síncrono
var result = repos.QueryPaginated(filter).Paginate(1, 10);

Com ordenação

var result = await repos.QueryPaginated(filter)
    .OrderBy(new[] { "Name" })
    .Descending()
    .PaginateAsync(page: 1, pageSize: 20);

Console.WriteLine($"Total: {result.TotalCount}, Página: {result.Page}/{result.PageCount}");

Nota: o QueryPaginated também aceita Paginate(page, pageSize) (sync) e PaginateAsync(page, pageSize) (async), ambos recebendo os delimitadores de página e tamanho.


🗄️ 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.

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.7.5 0 8/10/2026
1.6.8 0 8/9/2026
1.6.3 0 8/9/2026
1.6.2 28 8/9/2026
1.6.0 43 8/8/2026
1.4.0 40 8/7/2026
1.3.0 437 11/30/2025
1.2.8 414 6/1/2025
1.2.7 558 3/13/2025
Loading failed

v1.7.5: Fix critical NullReferenceException in EntityReflector.IsEmptyObjectValue when null values passed during FillComposition (eager loading); Query() returns IQueryBuilder; QueryPaginated() returns IQueryPaginatedBuilder; QueryRaw/QueryRawSync with SQL injection prevention; OrderBy and GroupBy accept string[]; awaitable builders; RelationalColumn/DataAggregationColumn for ETL/DW; Pluggable cache providers; parameterized queries. v1.6.8: date range by value type; null-safe ranges; empty string exclusion; KeyColumns cache by entity type. v1.6.6: [Table] and [Column] optional; enum as string literals; PostgreSQL compliant.