How to solve “The method 'Skip' is only supported for sorted input in LINQ to Entities.”

馋奶兔 提交于 2019-12-12 21:18:15

问题


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();

How can I fix it? What would happen if I put OrderBy instead of Where?


回答1:


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();

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.



来源:https://stackoverflow.com/questions/22800908/how-to-solve-the-method-skip-is-only-supported-for-sorted-input-in-linq-to-en

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!