2014-02-13 126 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

謝謝你,謝謝你,謝謝你!把我的頭髮拉出來。對這樣的表達式和函數沒有太多的經驗。 –

相關問題