使用进阶-动态排序

动态排序

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

var personQuery = context.Query<Person>();
personQuery = personQuery.OrderBy("Age asc,Id desc");/* 传入字符串,多个排序以 ',' 分隔 */
List<Person> persons = personQuery.ToList();
/*
 * SELECT [Person].[Name] AS [Name],[Person].[Gender] AS [Gender],[Person].[Age] AS [Age],[Person].[CityId] AS [CityId],[Person].[CreateTime] AS [CreateTime],[Person].[EditTime] AS [EditTime],[Person].[Id] AS [Id] 
   FROM [Person] AS [Person] 
   ORDER BY [Person].[Age] ASC,[Person].[Id] DESC
 */

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

var personQuery = context.Query<Person>();
var cityQuery = context.Query<City>();

/* 建立连接 */
var person_city = personQuery.LeftJoin(cityQuery, (person, city) => person.CityId == city.Id);

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

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