Rochas.DapperRepository 1.3.0

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

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

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

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

    [Column("age")]
    public int Age { get; set; }

    [Column("active")]
    public bool Active { get; set; }

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

[Table("child_entities")]
public class ChildEntity
{
    [Key]
    public int Id { get; set; }

    public int ParentId { get; set; }

    public string Description { get; set; }
}

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


⚡ Cache Interno usando [Cacheable]

Ao marcar a entidade:

[Cacheable]

O repositório ativa o gerenciamento automático de cache.

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

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

🔗 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; }
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.3.0 254 11/30/2025
1.2.8 275 6/1/2025
1.2.7 434 3/13/2025

Data caching concurrency issue fix