2014-02-13 99 views
6

试图将orderby语句添加到我的通用存储库方法并获取以下错误。不知道为什么,因为看起来我能够在其他情况下将.OrderBy添加到IQueryable。无法将Linq.IOrderedEnumerable <T>转换为Linq.IQueryable <T>

我错过了什么?

四处错误:

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Linq.IQueryable'

代码段(部​​分删除):

public class QuickbooksRespository<TEntity> 
     where TEntity : class, Intuit.Ipp.Data.IEntity, new() 
    { 
    public virtual IQueryable<TEntity> GetAll(
     int page, int pageSize, 
     Func<TEntity, object> orderbyascending = null, 
     Func<TEntity, object> orderbydescending = null) 
    { 
     int skip = Math.Max(pageSize * (page - 1), 0); 

     IQueryable<TEntity> results = _qbQueryService 
       .Select(all => all); 

     if (orderbyascending != null) 
     { 
      results = results.OrderBy(orderbyascending); 
     } 

     if (orderbydescending != null) 
     { 
      results = results.OrderByDescending(orderbydescending); 
     } 

     return results 
       .Skip(skip) 
       .Take(pageSize); 
    } 
} 

回答

12

因为你提供Func<...>委托,选择IEnumerable.OrderBy扩展方法。更改方法参数Expression<Func<...>>

public virtual IQueryable<TEntity> GetAll(
    int page, int pageSize, 
    Expression<Func<TEntity, object>> orderbyascending = null, 
    Expression<Func<TEntity, object>> orderbydescending = null) 

它将使IQueryable.OrderBy()方法是选择,而不是IEnumerable.OrderBy()实际上当你调用OrderBy()以后。

+1

谢谢你,谢谢你,谢谢你!把我的头发拉出来。对这样的表达式和函数没有太多的经验。 –

相关问题