Multiple “order by” in LINQ

后端 未结 7 1635
小蘑菇
小蘑菇 2020-11-22 00:16

I have two tables, movies and categories, and I get an ordered list by categoryID first and then by Name.

7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 00:41

    use the following line on your DataContext to log the SQL activity on the DataContext to the console - then you can see exactly what your linq statements are requesting from the database:

    _db.Log = Console.Out
    

    The following LINQ statements:

    var movies = from row in _db.Movies 
                 orderby row.CategoryID, row.Name
                 select row;
    

    AND

    var movies = _db.Movies.OrderBy(m => m.CategoryID).ThenBy(m => m.Name);
    

    produce the following SQL:

    SELECT [t0].ID, [t0].[Name], [t0].CategoryID
    FROM [dbo].[Movies] as [t0]
    ORDER BY [t0].CategoryID, [t0].[Name]
    

    Whereas, repeating an OrderBy in Linq, appears to reverse the resulting SQL output:

    var movies = from row in _db.Movies 
                 orderby row.CategoryID
                 orderby row.Name
                 select row;
    

    AND

    var movies = _db.Movies.OrderBy(m => m.CategoryID).OrderBy(m => m.Name);
    

    produce the following SQL (Name and CategoryId are switched):

    SELECT [t0].ID, [t0].[Name], [t0].CategoryID
    FROM [dbo].[Movies] as [t0]
    ORDER BY [t0].[Name], [t0].CategoryID
    

提交回复
热议问题