LINQ Entity Framework Ordered Sequences for Skip Operator
By Indranil Chatterjee
In spite of supporting a similar set of operations, LINQ to objects and LINQ to Entities have some subtle differences. The Skip operator is one of them. This FAQ tried to explain the importance of an ordered sequence in order to apply the Skip operator.
We often need to apply pagination on a data source. A simple way to do that using
LINQ is to apply Skip and Take successively as follows:
myCustomers.Skip(2).Take(3); //This should ignore the first 2 and return the next 3 customers from the sequence
However, if you're using Entity Framework, beware. This will throw a System.NotSupportedException
with the following message:
The method 'Skip' is only supported for sorted input in LINQ to Entities. The method
'OrderBy' must be called before the method 'Skip'.
The reason is, LINQ to Entities does not support the Skip operator on sequences that
are not ordered. So we have to either apply OrderBy or OrderByDescending on the
sequence before applying Skip.
We can avoid the error If we do something like the following:
myCustomers.OrderBy(c => c.CustomerId).Skip(2).Take(3);
LINQ Entity Framework Ordered Sequences for Skip Operator (1691 Views)