I'm trying to create a generic repository in .NET that can handle dynamic pagination, filtering, sorting, column selection, and related entity includes. The goal is to make the repository flexible enough for different use cases without having to manually write queries for each scenario.
Is there a package or pattern that can help with this in .NET? Or should I be using a custom approach like dynamic LINQ or Specification Pattern? Any best practices or examples would be greatly appreciated!
This is my current approach. How should I modify it?
public abstract class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly EqpDbContext _dbContext;
private readonly DbSet<T> _dbSet;
public GenericRepository(EqpDbContext dbContext)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
}
public virtual async Task<List<T>> GetAllAsync(bool includeDeleted = false, CancellationToken cancellationToken = default)
{
var query = _dbSet.AsNoTracking();
if (PropertyExists("IsDeleted") && !includeDeleted)
{
query = query.Where(e => EF.Property<bool>(e, "IsDeleted") == false);
}
return await query.ToListAsync(cancellationToken);
}
public virtual async Task<T?> GetByIdAsync(int id, bool includeDeleted = false, CancellationToken cancellationToken = default)
{
var query = _dbSet.AsQueryable().AsNoTracking();
if (PropertyExists("IsDeleted") && !includeDeleted)
{
query = query.Where(e => EF.Property<bool>(e, "IsDeleted") == false);
}
return await query.FirstOrDefaultAsync(e => EF.Property<int>(e, "Id") == id, cancellationToken: cancellationToken);
}