Querying Entity Model. Part 17 – ORDER BY

LINQ supplies 4 methods to order the result set, and all these methods are implemented in Entity Framework. The first method should be OrderBy() for ascending ordering or OrderByDescending() otherwise. The second and next subsequent methods should be ThenBy() or ThenByDescending().

This LINQ query will generate the following T-SQL code on the model used in all my posts about Querying Entity Model.

Good! Entity Framework produces the correct ORDER BY clause.

If you place two OrderBy() methods in one LINQ query one after another, you’ll get a wrong result – it will be sorted only by the last expression.

So the correct sequence must be OrderBy – ThenBy.

Leave a Reply

Your email address will not be published. Required fields are marked *