Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 690
Trung Pham Avatar asked Apr 02 '14 03:04

Trung Pham


People also ask

How do you use take and skip in LINQ?

The Take operator is used to return a given number of elements from an array and the Skip operator skips over a specified number of elements from an array. Skip, skips elements up to a specified position starting from the first element in a sequence.

What is Skip method in C#?

Use the Skip() method in C# to skip number of elements in an array. Let's say the following is our array − int[] arr = { 10, 20, 30, 40, 50 }; To skip the first two elements, use the Skip() method and add argument as 2 − arr.Skip(2);

Does LINQ order matter?

Yes. But exactly what that performance difference is depends on how the underlying expression tree is evaluated by the LINQ provider. For instance, your query may well execute faster the second time (with the WHERE clause first) for LINQ-to-XML, but faster the first time for LINQ-to-SQL.

Is LINQ select slow?

Let's start off by acknowledging that using the LINQ operators (such as Select and Where ) does typically result in very slighly slower code than if you wrote a for or foreach loop to do the same thing. This is acknowledged in the Microsoft documentation: LINQ syntax is typically less efficient than a foreach loop.


1 Answers

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.

like image 63
Simon Whitehead Avatar answered Sep 28 '22 02:09

Simon Whitehead