学习自B站杨旭老师asp.net core 3.0 web api 视频
老师B站名字(solenovex)
前言:普通的webapi对数据进行排序,大家肯定都会的,我之前是用的很多if else或者switch case 来进行的排序,那么这就会产生一个巨大的缺点,就是代码量较大,而且需要写很多的重复性代码。今天跟杨老师学习了一种新的排序方法,旨再可以使所有的排序复用,可以把排序方法写到辅助类中。那么,开始之前,我先给大家看一下真正需要写到serviderprovider中的内容到底有多少,就像下图看见的,只有两行用于排序。
public List<Employee> Get(string order)
{
IQueryable<Employee> query = _context.Employees.Where(e=>true);
var mappingDictionary = _propertyMappingService.GetPropertyMapping<EmployeeDto, Employee>();
var items = query.ApplySort(order, mappingDictionary);
return items.ToList();
}
一、排序遇到的问题
- 映射:Name:FirstName + LastName
- 应用排序。但是目前只能使用string,而不是lambda表达式
·System.Linq.Dynamic.Core 这个Linq扩展库 - 复用性
·针对IQueryable的一个扩展方法?
二、属性映射服务
需求:
- 一个资源(DTO)的属性可以映射到Entity上面多个属性
·Name:FirstName LastName - 映射可能需要反转顺序
·Age asc:DateOfBirth desc
服务:
- PropertyMappingService:IPropertyMappingService
·IList<IPropertyMapping> propertyMappings 例如:EmployeeDto:Employee
·PropertyMapping<TSource, TDestination>:IPropertyMapping
·Dictionary<string, PropertyMappingValue>
·PropertyMappingValue
·DestinationProperties 例如 FirstName LastName
·Revert 例如 true:Age→DateOfBirth
·GetPropertyMapping<TSource,TDestination>() 例如从EmployeeDto到Employee
上图不是实际代码,只是一个为了满足这两个要求的设想
这个服务可以帮助我们完成以上两个需求
我们先看一下为了满足上面两个需求而创建的类:
using System;
using System.Collections.Generic;
namespace SortProject.Services
{
public class PropertyMappingValue
{
public IEnumerable<string> DestinationProperties {
get; set; }
public bool Revert {
get; set; }
public PropertyMappingValue(IEnumerable<string> destinationProperties, bool revert = false)
{
DestinationProperties = destinationProperties ?? throw new ArgumentException(nameof(destinationProperties));
Revert = revert;
}
}
}
其中,DestinationProperties是可枚举类型 是我们为了解决像 Name:FirstName LastName这种一个DTO中的字段对应多个实体字段而安排的,
revert是为了解决 Age asc:DateOfBirth desc 这种相反顺序而安排的。
以下是属性映射服务的代码:
using System;
using System.Collections.