1、首先,准备测试数据如下:
2、Linq的排序方式,下面的例子是根据RoleId升序、Name降序
1 EFContext<Member> efMemberContext = new EFContext<Member>(); 2 var memberSet = efMemberContext.Set<Member>().Include("Role"); 3 4 var linq= from m in memberSet 5 orderby m.RoleId ascending, m.Name descending //根据RoleId升序、Name降序 6 select m; 7 8 foreach (Member item in linq) 9 { 10 Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name);}
输出结果如下:
SQL Profiler如下:
3、同样的方式如果用Lambda排序,先猜想如下:
1 EFContext<Member> efMemberContext = new EFContext<Member>(); 2 var memberSet = efMemberContext.Set<Member>().Include("Role"); 3 //根据RoleId升序、Name降序 4 var memberList = memberSet.OrderBy(m => m.RoleId).OrderByDescending(m => m.Name); 5 foreach (Member item in memberList) 6 { 7 Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name); 8 }
运行程序发现与linq方式的不一致,结果如下:
SQL Profiler如下:
4、发现连续调用OrderBy或者OrderByDescending之后,以最后一个为准排序,这时ThenBy就派上了用场。
ThenBy是使用OrderBy或者OrderByDescending之后,再次对结果进行二次排序
1 EFContext<Member> efMemberContext = new EFContext<Member>(); 2 var memberSet = efMemberContext.Set<Member>().Include("Role"); 3 //根据RoleId升序之后使用ThenByDescending对结果进行二次排序 4 var memberList = memberSet.OrderBy(m => m.RoleId).ThenByDescending(m => m.Name); 5 foreach (Member item in memberList) 6 { 7 Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name); 8 }
结果如下:
SQL Profiler如下:
5、如果想数据库中多个列排序一致,可以先OrderBy(或者OrderByDescending)后ThenBy(或者ThenByDescending),
也可以在OrderBy或者OrderByDescending直接指定多个属性,这样生成的SQL就是多个列的排序(排序一致asc/desc)
1 EFContext<Member> efMemberContext = new EFContext<Member>(); 2 var memberSet = efMemberContext.Set<Member>().Include("Role"); 3 //orderby 指定多个属性 4 var memberList = memberSet.OrderBy(m => new { m.RoleId, m.Name }); 5 foreach (Member item in memberList) 6 { 7 Console.WriteLine("{0},Role:{1}",item.Name,item.Role.Name); 8 }
结果如下:
SQL Profiler如下: