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
?
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.
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With