使用Skip和Take in LINQ的OrderByDescending显示错误

Isa*_*ran 6 c# linq linq-to-entities entity-framework linq-to-sql

我的linq是东西

GetPublishedArticleList().Where(x => x.Category.CatName == catName).OrderByDescending(x=>x.PublishedDate).Skip(skip).Take(last);
Run Code Online (Sandbox Code Playgroud)

运行上面的代码时,我得到以下异常

"方法'Skip'仅支持LINQ to Entities中的排序输入.必须在方法'Skip'之前调用'OrderBy'方法.

好吧,我希望LINQ能够理解我需要先按降序排序数据然后才能应用Skip和Take.(以上代码在OrderBy替换OrderByDescending时有效)

有人可以建议我替代吗?

phi*_*ady 3

这适用于 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);
    }
Run Code Online (Sandbox Code Playgroud)