How should I expose the total record count and IEnumable collection of paged records from my service layer method?

不羁的心 提交于 2019-12-03 14:21:18
Eranga

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!