c# - OrderByDescending with Skip and Take 在 LINQ 中显示错误

标签 c# linq entity-framework linq-to-sql linq-to-entities

我的 linq 是个东西

GetPublishedArticleList().Where(x => x.Category.CatName == catName).OrderByDescending(x=>x.PublishedDate).Skip(skip).Take(last);

运行上述代码时出现以下异常

“只有 LINQ to Entities 中的排序输入才支持方法‘Skip’。必须在方法‘Skip’之前调用方法‘OrderBy’。

好吧,我想让 LINQ 明白我需要先按降序排列数据,然后才能应用 Skip 和 Take。 (当 OrderByDescending 被 OrderBy 替换时,上面的代码有效)

有人可以建议我替代方案吗?

最佳答案

这适用于 EF5。 (.net 4.5) 我看不出你的代码有什么问题。 您确定测试时方法顺序正确吗? 源类型是 Iqueryable 还是 Iqueryable?

public virtual IQueryable<TPoco> GetSortedPageList<TSortKey>(Expression<Func<TPoco, bool>>    predicate,
        Expression<Func<TPoco, TSortKey>> sortBy,
        bool descending,
        int skipRecords, int takeRecords) {
        if (!descending) {
            return Context.Set<TPoco>()
                 .Where<TPoco> predicate)
                .OrderBy(sortBy)
                .Skip(skipRecords)
                .Take(takeRecords);
        }
        return
            Context.Set<TPoco>()
                .Where<TPoco>(predicate)
                .OrderByDescending(sortBy)
                .Skip(skipRecords)
                .Take(takeRecords);
    }

关于c# - OrderByDescending with Skip and Take 在 LINQ 中显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18009634/

相关文章:

c# - 将项目加入单个列表<>

c# - 在 foreach 语句中使用 LINQ 从泛型 List<T> 中检索值

.NET/Entity Framework Core/SQL Server 过程返回重复值

c# - 在 View 中从 ViewModel 迭代 ICollection

c# - EntityFrameworkCore RoleManager FindByIdAsync 可以填充声明吗?

c# - 为传递给局部 View 的模型设置默认值

c# - 统一: how to specify to use specific instance of a type when resolving another type

c# - Unity Container中的构造函数注入(inject)多个实现

linq - XElement NullReferenceException

c# - Html.Raw 不工作 asp.net mvc