I implement a repository pattern in my pet-project and I have a little question about realization of methods which return collections of items (for example: GetAll, GetBy). In current implementation the code of that methods look like below:
public IEnumerable<T> GetAll()
{
return _context.Set<T>().ToList();
}
public IEnumerable<T> GetBy(Expression<Func<T, bool>> predicate)
{
return
predicate == null ?
throw new ArgumentNullException(nameof(predicate)) :
_context.Set<T>().Where(predicate).ToList;
}
public async Task<IEnumerable<T>> GetAllAsync()
{
return await _context.Set<T>().ToListAsync();
}
public async Task<IEnumerable<T>> GetByAsync(Expression<Func<T, bool>> predicate)
{
return
predicate == null ?
throw new ArgumentNullException(nameof(predicate)) :
await _context.Set<T>().Where(predicate).ToListAsync();
}
I think that casting to list is not a good idea, so I tried to rewrite my code with using "yield return" and Enumerable, like below:
public IEnumerable<T> GetAll()
{
foreach (var item in _context.Set<T>().AsEnumerable())
{
yield return item;
}
}
But I have not found sample how to implement async version of this code. Could you give me some advice about best implementation of this stuff?
Aucun commentaire:
Enregistrer un commentaire