当前位置:网站首页>对象到对象映射-AutoMapper
对象到对象映射-AutoMapper
2022-07-28 09:17:00 【biyusr】
AutoMapper 是一个对象-对象映射器,可以将一个对象映射到另一个对象。
用来解决一个看似复杂的问题,这种类型的代码编写起来相当枯燥乏味,
官网地址:
http://automapper.org/
官方文档:
https://docs.automapper.org/en/latest/
入门
AutoMapper支持使用静态服务位置构造“自定义值解析器”,“自定义类型转换器”和“值转换器”的功能:
var configuration = new MapperConfiguration(cfg =>{cfg.ConstructServicesUsing(ObjectFactory.GetInstance);cfg.CreateMap<Source, Destination>();});
或动态服务位置,用于基于实例的容器(包括子容器/嵌套容器):
var mapper = new Mapper(configuration, childContainer.GetInstance);var dest = mapper.Map<Source, Destination>(new Source { Value = 15 });
您可以使用配置文件定义配置。然后,通过在启动时调用IServiceCollection扩展方法AddAutoMapper,使AutoMapper知道这些概要文件在哪些程序集中定义:
services.AddAutoMapper(profileAssembly1, profileAssembly2 /*, ...*/);或标记类型:
services.AddAutoMapper(typeof(ProfileTypeFromAssembly1), typeof(ProfileTypeFromAssembly2) /*, ...*/);现在,您可以在运行时将AutoMapper注入服务/控制器中:
public class EmployeesController {private readonly IMapper _mapper;public EmployeesController(IMapper mapper) => _mapper = mapper;// use _mapper.Map or _mapper.ProjectTo}
当然还有很多可扩展性,比如:
定制类型转换器
有时,您需要完全控制从一种类型到另一种类型的转换。通常,这是当一种类型看起来与另一种类型不一样时,已经存在转换函数,并且您希望从“松散”类型变为更强的类型,例如字符串的源类型到Int32的目标类型。
例如,假设我们的源类型为:
public class Source{public string Value1 { get; set; }public string Value2 { get; set; }public string Value3 { get; set; }}
但您想将其映射到:
public class Destination{public int Value1 { get; set; }public DateTime Value2 { get; set; }public Type Value3 { get; set; }}
如果我们尝试按原样映射这两种类型,则AutoMapper会抛出异常(在映射时和配置检查时),因为AutoMapper不知道从字符串到int,DateTime或Type的任何映射。要为这些类型创建映射,我们必须提供一个自定义类型转换器,并且我们可以通过三种方式:
void ConvertUsing(Func<TSource, TDestination> mappingFunction);void ConvertUsing(ITypeConverter<TSource, TDestination> converter);void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;
第一个选项就是任何带有源并返回目的地的函数(也有多个重载)。这适用于简单的情况,但对于较大的情况则显得笨拙。在更困难的情况下,我们可以创建一个自定义的ITypeConverter <TSource,TDestination>:
public interface ITypeConverter<in TSource, TDestination>{TDestination Convert(TSource source, TDestination destination, ResolutionContext context);}
并向AutoMapper提供一个自定义类型转换器的实例,或者为类型提供AutoMapper将在运行时实例化的类型。我们上面的源/目标类型的映射配置将变为:
public void Example(){var configuration = new MapperConfiguration(cfg => {cfg.CreateMap<string, int>().ConvertUsing(s => Convert.ToInt32(s));cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();cfg.CreateMap<Source, Destination>();});configuration.AssertConfigurationIsValid();var source = new Source{Value1 = "5",Value2 = "01/01/2000",Value3 = "AutoMapperSamples.GlobalTypeConverters.GlobalTypeConverters+Destination"};Destination result = mapper.Map<Source, Destination>(source);result.Value3.ShouldEqual(typeof(Destination));}public class DateTimeTypeConverter : ITypeConverter<string, DateTime>{public DateTime Convert(string source, DateTime destination, ResolutionContext context){return System.Convert.ToDateTime(source);}}public class TypeTypeConverter : ITypeConverter<string, Type>{public Type Convert(string source, Type destination, ResolutionContext context){return Assembly.GetExecutingAssembly().GetType(source);}}
在第一个映射中,从字符串到Int32,我们仅使用内置的Convert.ToInt32函数(作为方法组提供)。接下来的两个使用自定义ITypeConverter实现。
自定义类型转换器的真正强大之处在于,只要AutoMapper在任何映射类型上找到源/目标对,它们就可以使用。我们可以构建一组自定义类型转换器,并在其上使用其他映射配置,而无需任何其他配置。在上面的示例中,我们不必再次指定string / int转换。由于必须在类型成员级别配置自定义值解析器,因此自定义类型转换器的作用域是全局的。
当然还有很多功能需要去实际项目中实现。
边栏推荐
- 咸鱼ESP32实例—MQTT 点亮LED
- Changes in the relationship between data and application in IT industry
- Hexadecimal representation of negative numbers
- My vivado practice - single cycle CPU instruction analysis
- Analysis of HashSet internal principle
- CakePHP 4.4.3 release, PHP rapid development framework
- Arouter source code analysis (I)
- 数据库核心体系
- 478-82(56、128、718、129)
- 时序分析41 - 时序预测 TBATS模型
猜你喜欢

Heuristic merging on tree

Salted fish esp32 instance - mqtt lit LED

Dn-detr paper accuracy, and analyze its model structure & 2022 CVPR paper

多线程一定能优化程序性能吗?

matlab基本操作

Introduction to shardingsphere (I)

Go language slice vs array panic runtime error index out of range problem solving

《PyTorch深度学习实践》第九课多分类问题(手写数字MNIST)

Regular expressions for positive and negative values

JS array is de duplicated, the ID is the same, and a value is added and merged
随机推荐
数据库高级学习笔记--游标
[autosar-rte] - 3-runnable and its task mapping mapping
《PyTorch深度学习实践》第九课多分类问题(手写数字MNIST)
MySQL 8.0.30 GA
C# 窗体应用使用对象绑定 DataGridView 数据绑定
Sequence and limit operation of MATLAB
Window源码解析(二):Window的添加机制
Changes in the relationship between data and application in IT industry
【广西大学】考研初试复试资料分享
IJCAI 2022 | 图结构学习最新综述:研究进展与未来展望
Technology sharing | quick intercom integrated dispatching system
[vscode] vscode usage
[multithreading] the underlying principle of println method
数据库高级学习笔记--系统包
关于CLR GC调优的一些问题
Introduction to shardingsphere (I)
网络工程——软科中国大学专业排名
IDC script file running
JS array is de duplicated, the ID is the same, and a value is added and merged
力扣376-摆动序列——贪心