使用进阶-动态排序

动态排序

在一些后台系统中,很多查询的排序字段是不定的,需要动态排序的场景不少。动态排序接口以扩展的形式实现,需要引用 Chloe.Extension.dll,nuget 安装命令:Install-Package Chloe.Extension
简单用法:
这种用法针对简单的实体。

var userQuery = context.Query<User>();
userQuery = userQuery.OrderBy("Age asc,Id desc");/* 传入字符串,多个排序以 ',' 分隔 */
List<User> users = userQuery.ToList();
/*
 * 生成的 sql:
 * SELECT [Users].[Gender] AS [Gender],[Users].[Age] AS [Age],[Users].[CityId] AS [CityId],[Users].[OpTime] AS [OpTime],[Users].[Id] AS [Id],[Users].[Name] AS [Name] 
   FROM [Users] AS [Users] 
   ORDER BY [Users].[Age] ASC,[Users].[Id] DESC
 */

高级用法:
当查询返回的类型是复杂类型的时候可以使用这种用法。

var userQuery = context.Query<User>();
var cityQuery = context.Query<City>();

/* 建立连接 */
var user_city = userQuery.LeftJoin(cityQuery, (user, city) => user.CityId == city.Id);

/* Select 返回的是一个复杂的匿名类型 */
var view = user_city.Select((user, city) => new { User = user, City = city });

/* 传入字符串排序 */
view = view.OrderBy("User.Age asc,User.Id desc");
var result = view.ToList();
/*
 * SELECT [Users].[Gender] AS [Gender],[Users].[Age] AS [Age],[Users].[CityId] AS [CityId],[Users].[OpTime] AS [OpTime],[Users].[Id] AS [Id],[Users].[Name] AS [Name],[City].[Id] AS [Id0],[City].[Name] AS [Name0],[City].[ProvinceId] AS [ProvinceId] 
   FROM [Users] AS [Users] 
   LEFT JOIN [City] AS [City] ON [Users].[CityId] = [City].[Id] 
   ORDER BY [Users].[Age] ASC,[Users].[Id] DESC
 */