gpt4 book ai didi

c# - 如何解决 "The method ' Skip' 仅支持 LINQ to Entities 中的排序输入。”

转载 作者:行者123 更新时间:2023-11-30 19:26:27 27 4
gpt4 key购买 nike

我在使用“LINQ to entities”显示每个产品并在 ASP.NET MVC 中实现分页时遇到此错误。

The method 'Skip' is only supported for sorted input in LINQ to Entities.
The method 'OrderBy' must be called before the method 'Skip'."

林克:

Model.Name = db.Products.Where(p => p.ProductSubcategoryID == id)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();

我该如何解决?如果我用 OrderBy 而不是 Where 会发生什么?

最佳答案

您不会“将 OrderBy 替换为 Where”...您将它们结合起来:

Model.Name = db.Products.Where(p => p.ProductSubcategoryID == id)
.OrderBy(p => p.ProductSubcategoryID) // <---- this
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();

这是必需的,因为生成的 SQL 将产生如下内容:

WHERE generated_id BETWEEN x AND y

如果您没有明确告诉数据库服务器返回结果的顺序......您的结果每次(可能)都会不同。然而,如果您按字段排序,则保证它们按顺序出现,因此您的分页将产生一致的结果。

关于c# - 如何解决 "The method ' Skip' 仅支持 LINQ to Entities 中的排序输入。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800908/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com