I have a WebAPI application. I’m using the Repository pattern, where the GetAll method returns an IQueryable collection to filter the data on the database side. Is it correct?
Here’s the interface:
public interface IBaseRepository<TEntity>
{
IQueryable<TEntity> GetAll();
Task<TEntity> CreateAsync(TEntity entity);
Task<TEntity> UpdateAsync(TEntity entity);
Task<TEntity> DeleteAsync(TEntity entity);
}
Here`s the implementation:
public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
{
private readonly ApplicationDbContext _dbContext;
public BaseRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<TEntity> CreateAsync(TEntity entity)
{
if (entity == null)
throw new ArgumentException("Entity is null");
await _dbContext.AddAsync(entity);
await _dbContext.SaveChangesAsync();
return entity;
}
public async Task<TEntity> DeleteAsync(TEntity entity)
{
if (entity == null)
throw new ArgumentException("Entity is null");
_dbContext.Remove(entity);
await _dbContext.SaveChangesAsync();
return entity;
}
public IQueryable<TEntity> GetAll()
{
return _dbContext.Set<TEntity>();
}
public async Task<TEntity> UpdateAsync(TEntity entity)
{
if (entity == null)
throw new ArgumentException("Entity is null");
_dbContext.Update(entity);
await _dbContext.SaveChangesAsync();
return entity;
}
}
This allows me to do database side filtering:
reports = await _reportRepository.GetAll()
.Where(x => x.UserId == userId)
.ToArrayAsync();
How correct is this approach? I recently heard that you need to return IEnumerable from the repository.