在分层设计模式中,各层之间的数据一般经过数据传输对象(DTO)来进行数据的传递,而大多数状况下,各层数据的定义结构大同小异,如何在这些定义结构中相互转换,以前咱们经过使用AutoMapper库,但AutoMapper功能庞大,使用较为复杂,而在不少场景下,可能咱们只须要一些基础的对象映射功能,那么此时你能够选择扩展库中的轻量级AutoMapper实现。git
实体映射包含如下核心功能:github
启用轻量级的实体映射,有两种方式:c#
using IHost host = Host.CreateDefaultBuilder() // UseExtensions会自动注入Mapper .UseExtensions() .ConfigureServices(sc => { // 经过ConfigureLightweightMapper来配置映射 sc.ConfigureLightweightMapper(options => { // }); }) .Build();
//实体转换 serviceDescriptors.AddLightweightMapper() .ConfigureLightweightMapper(options => { // });
你能够经过映射设置上的AddConvert来配置对应设置实体转换的后置
逻辑,以下所示。设计模式
//实体转换 serviceDescriptors.AddLightweightMapper() .ConfigureLightweightMapper(options => { // 经过AddConvert可自定义转换逻辑 // 如下定义从SourceA转换到TargetB时,自动设置属性C的值 options.AddConvert<SourceA, TargetB>((mapper, a, b) => { b.C = "C"; }); });
你能够经过IMapperProvider的GetMapper方法或IMapper<,>直接获取Mapper实例。缓存
// 经过IMapperProvider var mapperProvider = host.Services.GetRequiredService<IMapperProvider>(); var mapper = mapperProvider.GetMapper<SourceA, TargetA>(); var targetA = mapper.Convert(sourceA);
var mapperB = host.Services.GetRequiredService<IMapper<SourceA, TargetB>>(); var targetB = mapperB.Convert(sourceA);
默认映射按照属性名称进行,你也能够经过MapperPropertyNameAttribute特性进行指定。app
MapperPropertyNameAttribute:ide
属性名 | 类型 | 说明 |
---|---|---|
Name | String | 目标或源的名称 |
TargetType | Type | 映射到的目标类型 |
SourceType | Type | 映射到当前类型的来源类型 |
经过SourceType或TargetType你能够根据需求灵活的在源类型或目标类型上设置映射关系。性能
实体映射也提供了拷贝方法,经过该方法能够将源实体属性拷贝到目标实体。ui
var mapperB = host.Services.GetRequiredService<IMapper<SourceA, TargetB>>(); var targetB1 = new TargetB(); mapperB.CopyTo(sourceA, targetB1);
var mapperB = host.Services.GetRequiredService<IMapper<SourceA, TargetB>>(); // 只拷贝指定字段以外的属性 var copyProc = mapperB.DefineCopyTo(a => new { a.A //忽略属性A }); var targetB2 = new TargetB(); copyProc(sourceA, targetB2);
以上示例完整项目,请参考GitHub示例设计