• AutoMapper的简单使用


    1. 第一种方法,推荐!

    添加一个功能类

    using AutoMapper;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace AutoMapperTest2
    {
        public static class AutoMapperConfig
        {
            public static IMapper Mapper = new Mapper(RegisterMappings());
    
            public static MapperConfiguration RegisterMappings()
            {
                return new MapperConfiguration(cfg =>
                {
                    cfg.CreateMissingTypeMaps = true;
                    cfg.AllowNullDestinationValues = false;
                    cfg.ForAllPropertyMaps(IsToRepeatedField, (propertyMap, opts) => opts.UseDestinationValue());
                    cfg.ForAllPropertyMaps(IsToMapFieldField, (propertyMap, opts) => opts.UseDestinationValue());
    
                    cfg.AddProfile<OutputModels>();
                });
    
                bool IsToRepeatedField(PropertyMap pm)
                {
                    if (pm.DestinationPropertyType.IsConstructedGenericType)
                    {
                        var destGenericBase = pm.DestinationPropertyType.GetGenericTypeDefinition();
                        return false;// destGenericBase == typeof(RepeatedField<>);
                    }
                    return false;
                }
    
                bool IsToMapFieldField(PropertyMap pm)
                {
                    if (pm.DestinationPropertyType.IsConstructedGenericType)
                    {
                        var destGenericBase = pm.DestinationPropertyType.GetGenericTypeDefinition();
                        return false;// destGenericBase == typeof(MapField<,>);
                    }
                    return false;
                }
            }
        }
    
        public class OutputModels : Profile
        {
            public OutputModels()
            {
            }
        }
    }

    使用

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace AutoMapperTest2
    {
        class Program
        {
            static void Main(string[] args)
            {
                var src = new source() {
                    name = "jeff",
                    age  = 1,
                    strList = new List<string>() { "1", "2", "3"},
                    classList = new List<aaa>()
                    {
                        new aaa(){a1="a1", a2=1},
                         new aaa(){a1="a2", a2=2},
                          new aaa(){a1="a3", a2=3},
                    }
                };
                var tgt = AutoMapperConfig.Mapper.Map<target>(src);
                if (tgt != null)
                    Console.WriteLine($"name = {tgt.name}");
            }
        }
    
        public class source
        {
            public string name { get; set; }
            public int age { get; set; }
            public List<string> strList { get; set; }
            public List<aaa> classList { get; set; }
        }
    
        public class target
        {
            public string name { get; set; }
            public int age { get; set; }
            public List<string> strList { get; set; }
            public List<aaa> classList { get; set; }
    
    
        }
    
        public class aaa
        {
            public string a1 { get; set; }
            public int a2 { get; set; }
        }
    }

    2. 第二种方法:

    添加功能类

    using AutoMapper;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace TCG.DataCollection.Webservice { public sealed class Mapper { private static readonly Mapper instance = new Mapper(); private Mapper() { this.Init(); } public void Init() { AutoMapper.Mapper.Initialize(cfg => { departmentMapping(cfg); this.employeeMapping(cfg);this.defaultMapping<JobCoder, JobCodeModel>(cfg); this.defaultMapping<EmployeeTerminationData, EmployeeTerminationDataModel>(cfg); this.vestingMapping(cfg); }); } public static Dest Map<Src, Dest>(Src src) { if (instance != null) return AutoMapper.Mapper.Map<Src, Dest>(src); else throw new Exception("Automapper not initialized."); // TODO: 错误信息需集中定义。 } /// <summary> /// 提供默认的类型映射,双向映射,依据属性名称 /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <param name="cfg"></param> private void defaultMapping<T1, T2>(IMapperConfigurationExpression cfg) { cfg.CreateMap<T1, T2>(); cfg.CreateMap<T2, T1>(); } private void departmentMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap<Department, DepartmentModel>() .ForMember(dest => dest.ParentDepartmentCode, options => options.MapFrom(src => string.IsNullOrWhiteSpace(src.ParentDepartmentCode) ? src.DepartmentCode : src.ParentDepartmentCode)); cfg.CreateMap<DepartmentModel, Department>() .ForMember(dest => dest.ParentDepartmentCode, options => options.MapFrom(src => src.ParentDepartmentCode)); } private void vestingMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap<Vesting, VestingModel>() .ForMember(dest => dest.VestingDate, options => options.ResolveUsing<DateTime>(src => this.convertDate(src.VestingDate).GetValueOrDefault())); } private void grantMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap<Grant, GrantModel>() .ForMember(dest => dest.GrantDate, options => options.ResolveUsing<DateTime>(src => { return this.convertDate(src.GrantDate).GetValueOrDefault(); })) .ForMember(dest => dest.GrantType, options => options.ResolveUsing<string>(src => this.convertGrantType(src.GrantType))) .ForMember(dest => dest.IsPerformanceBased, options => options.ResolveUsing<bool>(src => string.Equals(src.IsPerformanceBased, "Y", StringComparison.OrdinalIgnoreCase))); } private void reinstatementMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap<ReinstatementData, ReinstatementDataModel>() .ForMember(dest => dest.ReinstatementDate, options => options.ResolveUsing<DateTime>(src => this.convertDate(src.ReinstatementDate).GetValueOrDefault())) .ForMember(dest => dest.Type, options => options.UseValue<ReinstatementType>(ReinstatementType.R)); } private void employeeMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap<Employee, EmployeeModel>() .ForMember(dest => dest.SAFEforSubsequentSalse, options => options.ResolveUsing<string>(src => string.Equals(src.SAFEforSubsequentSalse, "Y", StringComparison.OrdinalIgnoreCase) ? "1" : string.Empty)); } private DateTime? convertDate(string date) { if (string.IsNullOrEmpty(date)) return null; var year = int.Parse(date.Substring(0, 4)); var month = int.Parse(date.Substring(4, 2)); var day = int.Parse(date.Substring(6, 2)); return new DateTime(year, month, day); } } }

    使用时

    var model = Mapper.Map<Employee, EmployeeModel>(data);
  • 相关阅读:
    RPC简介
    RabbitMQ从入门到精通
    flask 源码解析:响应
    flask 源码解析:请求
    flask 源码解析:上下文
    flask 源码解析:应用启动流程
    flask 源码解析:路由
    flask源码分析—简介
    11-Docker网络扩展
    10-Docker之Docker-Compose
  • 原文地址:https://www.cnblogs.com/itjeff/p/10175674.html
Copyright © 2020-2023  润新知