尝试将orderby
语句添加到我的通用存储库方法并获取以下错误。不知道为什么我似乎能够在其他情况下将.OrderBy添加到IQueryable。
我错过了什么?
获取错误:
无法将类型'System.Linq.IOrderedEnumerable'隐式转换为'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);
}
}
答案 0 :(得分:14)
由于您提供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()
。