How should I expose the total record count and IEnumable collection of paged records from my service layer method?
You can do something like this
public class Repository<TEntity>{ public IEnumerable<TEntity> GetCollection(Expression<Func<TEntity, bool>> filter, int pageSize, int pageIndex) { return YourDbSet.Where(filter).OrderBy(sortExpression).Skip(pageSize * pageIndex).Take(pageSize); } public int Count(Expression<Func<TEntity, bool>> filter) { return YourDbSet.Where(filter).Count(); }}
Then You can write an extension method to use both of these methods
public static Pagination<TEntity> GetPagination<TEntity>(this Repository<TEntity> repository, Expression<Func<TEntity, bool>> filter, int pageSize, int pageIndex){ var entities = repository.GetCollection(filter, pageSize, pageIndex); var count = repository.Count(filter); return new Pagination(entities, pageSize, pageIndex + 1, count);}
This way you can reuse GetCollection
and Count
methods independently.You can build the where condition dynamically. Take a look at my answer
If the Enumerable
you are returning contains all the items, I would do a ToList()
on it before returning if from the function. (you can then do Count
with no cost on it)If the function is returning a sub set of the total (using Skip
and take
) I would add a seperate function to get the total count.