c# – 无法将Linq.IOrderedEnumerable转换为Linq.IQueryable

尝试将orderby语句添加到我的通用存储库方法并获取以下错误.不知道为什么我似乎能够在其他情况下将.OrderBy添加到IQueryable.

我错过了什么?

得到错误:

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);
    }
}
最佳答案
因为你提供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)

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

转载注明原文:c# – 无法将Linq.IOrderedEnumerable转换为Linq.IQueryable - 代码日志