Rapid.GenericRepositoryPattern
1.0.0
dotnet add package Rapid.GenericRepositoryPattern --version 1.0.0
NuGet\Install-Package Rapid.GenericRepositoryPattern -Version 1.0.0
<PackageReference Include="Rapid.GenericRepositoryPattern" Version="1.0.0" />
paket add Rapid.GenericRepositoryPattern --version 1.0.0
#r "nuget: Rapid.GenericRepositoryPattern, 1.0.0"
// Install Rapid.GenericRepositoryPattern as a Cake Addin #addin nuget:?package=Rapid.GenericRepositoryPattern&version=1.0.0 // Install Rapid.GenericRepositoryPattern as a Cake Tool #tool nuget:?package=Rapid.GenericRepositoryPattern&version=1.0.0
Rapid.GenericRepositoryPattern
A comprehensive Generic Repository Pattern implementation for .NET applications with advanced features including async operations, specifications pattern, Entity Framework Core integration, caching, and more.
Features
- Generic CRUD operations with async support
- Unit of Work pattern implementation
- Specification pattern for complex queries
- Pagination and sorting capabilities
- Built-in caching mechanism
- Soft delete support
- Audit logging
- Transaction management
- Bulk operations
- Strongly typed repositories
- Entity Framework Core integration
- Dependency Injection support
Installation
Install the package via NuGet:
dotnet add package Rapid.GenericRepositoryPattern
Quick Start
1. Basic Setup
Register the services in your Program.cs
or Startup.cs
:
services.AddGenericRepository<YourDbContext>(options =>
{
options.EnableCaching = true;
options.DefaultCacheDurationMinutes = 30;
options.EnableSoftDelete = true;
options.EnableAuditLogging = true;
});
2. Create Your Entities
public class Customer : BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
// BaseEntity includes audit and soft delete properties
}
3. Use in Your Services
public class CustomerService
{
private readonly IRepository<Customer> _repository;
private readonly IUnitOfWork _unitOfWork;
public CustomerService(IRepository<Customer> repository, IUnitOfWork unitOfWork)
{
_repository = repository;
_unitOfWork = unitOfWork;
}
public async Task<Customer> CreateCustomerAsync(Customer customer)
{
await _unitOfWork.BeginTransactionAsync();
try
{
var result = await _repository.AddAsync(customer);
await _unitOfWork.CommitTransactionAsync();
return result;
}
catch
{
await _unitOfWork.RollbackTransactionAsync();
throw;
}
}
}
Advanced Usage
Specification Pattern
public class ActiveCustomersSpecification : BaseSpecification<Customer>
{
public ActiveCustomersSpecification()
: base(c => !c.IsDeleted)
{
AddInclude(c => c.Orders);
ApplyOrderBy(q => q.OrderByDescending(c => c.CreatedAt));
ApplyPaging(1, 10);
}
}
// Usage
var spec = new ActiveCustomersSpecification();
var customers = await _repository.GetAsync(spec.Criteria);
Bulk Operations
// Bulk Insert
await dbSet.BulkInsertAsync(newCustomers, batchSize: 1000);
// Bulk Update
await dbSet.BulkUpdateAsync(
x => x.Status == Status.Pending,
x => new Customer { Status = Status.Processed }
);
// Bulk Delete
await dbSet.BulkDeleteAsync(x => x.LastModifiedAt < DateTime.UtcNow.AddYears(-1));
Pagination and Sorting
// Using extension methods
var pagedResult = await dbSet
.ApplyOrder("Name", isDescending: false)
.ToPagedResultAsync(
pageIndex: 1,
pageSize: 10,
projection: x => new CustomerDto
{
Id = x.Id,
Name = x.Name
}
);
// Access pagination info
Console.WriteLine($"Total Items: {pagedResult.TotalCount}");
Console.WriteLine($"Total Pages: {pagedResult.TotalPages}");
Console.WriteLine($"Has Next Page: {pagedResult.HasNextPage}");
Caching
// Enable caching in registration
services.AddGenericRepository<YourDbContext>(options =>
{
options.EnableCaching = true;
options.DefaultCacheDurationMinutes = 60;
});
// Cache is automatically handled
var customers = await _repository.GetAsync(x => x.IsActive);
// Results are cached for 60 minutes
Audit Logging
// Audit information is automatically captured
public class AuditableDbContext : DbContext
{
private readonly ICurrentUserService _currentUserService;
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
// Automatically sets CreatedBy, CreatedAt, LastModifiedBy, LastModifiedAt
return await base.SaveChangesAsync(cancellationToken);
}
}
Best Practices
Use Unit of Work for Transactions
await _unitOfWork.BeginTransactionAsync(); try { // Perform multiple operations await _unitOfWork.CommitTransactionAsync(); } catch { await _unitOfWork.RollbackTransactionAsync(); throw; }
Implement Custom Repositories When Needed
public class CustomCustomerRepository : Repository<Customer> { public CustomCustomerRepository(DbContext context) : base(context) { } public async Task<List<Customer>> GetPremiumCustomers() { return await DbSet.Where(x => x.IsPremium).ToListAsync(); } }
Use Specifications for Complex Queries
public class CustomerByRegionSpecification : BaseSpecification<Customer> { public CustomerByRegionSpecification(string region) : base(c => c.Region == region) { AddInclude(c => c.Orders); ApplyOrderBy(q => q.OrderBy(c => c.Name)); } }
Handle Soft Delete
// Soft delete is automatically handled await _repository.DeleteAsync(entity); // Entity is marked as deleted but not physically removed
Use Projection for Performance
var dtos = await dbSet.ProjectToListAsync( x => new CustomerDto { Id = x.Id, Name = x.Name } );
Performance Considerations
- Use Projections: Always project to DTOs when you don't need the entire entity.
- Enable Caching: Use caching for frequently accessed, rarely changed data.
- Batch Operations: Use bulk operations for large datasets.
- Pagination: Always use pagination for large result sets.
- Eager Loading: Use Include statements judiciously to avoid N+1 queries.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. |
-
net9.0
- Microsoft.EntityFrameworkCore (>= 9.0.0)
- Microsoft.EntityFrameworkCore.Relational (>= 9.0.0)
- Microsoft.Extensions.Caching.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Caching.Memory (>= 9.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.0)
- System.Linq.Dynamic.Core (>= 1.5.1)
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.0.0 | 2,952 | 12/16/2024 |