zoukankan      html  css  js  c++  java
  • 对象映射工具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/



  • 相关阅读:
    WPF基础篇之控件模板(ControlTemplate)
    WPF基础篇之移动特效
    WPF基础篇之空间布局
    00-API-Mongoose
    00-API-Vue
    博客园皮肤设置
    15-Node
    16-Vue-A
    15-MongoDB
    14-电商项目
  • 原文地址:https://www.cnblogs.com/-simplelife/p/8609360.html
Copyright © 2011-2022 走看看