对象映射工具Mapper


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


1.AutoMapper

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

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

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

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/



posted on 2018-03-20 15:04  蓝色的云  阅读(716)  评论(0编辑  收藏  举报

导航