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().
1 2 3 |
var query17 = ctx.Clients .OrderBy(c => c.CountryCode) .ThenByDescending(c => c.Name); |
This LINQ query will generate the following T-SQL code on the model used in all my posts about Querying Entity Model.
1 2 3 4 5 6 7 |
SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], [Extent1].[CountryCode] AS [CountryCode], [Extent1].[Timestamp] AS [Timestamp] FROM [dbo].[Clients] AS [Extent1] ORDER BY [Extent1].[CountryCode] ASC, [Extent1].[Name] DESC |
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.
1 2 3 |
var query17 = ctx.Clients .OrderBy(c => c.CountryCode) .OrderByDescending(c => c.Name); |
1 2 3 4 5 6 7 |
SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], [Extent1].[CountryCode] AS [CountryCode], [Extent1].[Timestamp] AS [Timestamp] FROM [dbo].[Clients] AS [Extent1] ORDER BY [Extent1].[Name] DESC |
So the correct sequence must be OrderBy – ThenBy.