开发者

Linq Generic OrderBy selector

I am using the repository pattern in a asp.net mvc application (v3) and EntityFramework (v4). I would like to add to the repository paging functionality. I have the following sample code:

public PagedResult<T> GetPaged(int offset = 0, int limit = PagedResult<T>.NoLimit, Expression<Func<T, bool>> predicate = null) 
    {      
      var res = BaseQ.Where(_predicate);//.Skip(offset);
      if (predicate != null)
        res = res.Where(predicate);

      res = res.Skip(offset);

      if (limit != PagedResult<T>.NoLimit)
      {
 开发者_开发百科       res = res.Take(limit);
      }

      return new PagedResult<T>(res, res.Count(), offset, limit);
    }

However, this will not work because Entity framework throws an exception that I should call OrderBy before Skip. I am wondering how can I implement this in a generic way so that the order by expression will be plugged in from the outside. I would then pass it as a parameter. Perhaps there is also another way of working around that problem.

[EDIT] I found out that this can be done by passing in the name of the property and creating an expression out of that, but I would like to actually just use it as I am using it in the OrderBy. So just pass in (c=>c.ID) for example.

Thanks in advance for any ideas


I have decided to go with passing in a string and creating the expression from it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜