如何解决“方法'Skip'仅支持LINQ to Entities中的排序输入." [英] How to solve "The method 'Skip' is only supported for sorted input in LINQ to Entities."
问题描述
当我使用"LINQ到实体"来显示每个产品并在ASP.NET MVC中实现分页时,出现了此错误.
I got this error when I was using "LINQ to entities" to show every single product and implement paging in 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'."
LINQ:
Model.Name = db.Products.Where(p => p.ProductSubcategoryID == id)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();
我该如何解决?如果我放OrderBy
而不是Where
会怎样?
How can I fix it? What would happen if I put OrderBy
instead of Where
?
推荐答案
您不要用OrderBy
代替Where
" ...而是将它们组合在一起:
You don't "put OrderBy
instead of Where
"...you combine them:
Model.Name = db.Products.Where(p => p.ProductSubcategoryID == id)
.OrderBy(p => p.ProductSubcategoryID) // <---- this
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();
这是必需的,因为生成的SQL会产生类似以下内容的信息:
This is required because the generated SQL will produce something like:
WHERE generated_id BETWEEN x AND y
如果您没有明确告诉数据库服务器返回结果的顺序,则您的结果每次(可能)都将有所不同.而如果您按字段排序,则可以保证它们按顺序排列出来,因此您的分页将产生一致的结果.
If you don't explicitly tell the DB server what order to return results in...your results would be different (possibly) every time. Whereas, if you order by a field, they are guaranteed to come out in order and therefore your paging will produce consistent results.
这篇关于如何解决“方法'Skip'仅支持LINQ to Entities中的排序输入."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!