对象映射工具Mapper


对象Mapper工具备好几种,好比:AutoMapper、EmitMapper、ValueInjecter,通过比较比较推荐ValueInjecter。


1.AutoMapper

属性的命名要按照PascalCase命名规则

不一样类型的转换会报异常AutoMapperMappingException,-----解决方法(AutoMapper提供了自定义类型转换器)

ConvertUsing是什么?它是咱们在指定类型映射时,类型配置的方法,就是说经过ConvertUsing方法把类型映射中类型转换的权限交给用户配置,而不是经过AutoMapper进行自动类型转换,这就给我提供了更多的自定义性,也就避免了不一样类型之间转换而引发的”AutoMapperMappingException“异常app

public void Example() { var source = new Source { Value1 = "5", Value2 = "01/01/2000", Value3 = "DTO_AutoMapper使用详解.GlobalTypeConverters+Destination" }; // 配置 AutoMapper
            Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32); Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter()); Mapper.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>(); Mapper.CreateMap<Source, Destination>(); Mapper.AssertConfigurationIsValid(); // 执行 mapping
            Destination result = Mapper.Map<Source, Destination>(source); Console.WriteLine("result.Value1:" + result.Value1.ToString()); Console.WriteLine("result.Value2:" + result.Value2.ToString()); Console.WriteLine("result.Value3:" + result.Value3.ToString()); } Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.Total, opt => opt.MapFrom(src => src.Value1 + src.Value2));


2.EmitMapper------http://emitmapper.codeplex.com/

EmitMapper映射效率比较高,接近硬编码。EmitMapper采用emit方式在运行时动态生成IL,而其余映射框架可能是采用反射机制。此外EmitMapper最大限度地减小了拆箱装箱操做和映射过程当中的额外的调用
EmitMapper的使用很是简单,不须要指定任何的映射策略。系统会采用默认的映射配置器DefaultMapConfig完成映射操做



3.ValueInjecter-------https://valueinjecter.codeplex.com/



框架

相关文章
相关标签/搜索