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(); }); 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() { "1", "2", "3"}, classList = new List () { new aaa(){a1="a1", a2=1}, new aaa(){a1="a2", a2=2}, new aaa(){a1="a3", a2=3}, } }; var tgt = AutoMapperConfig.Mapper.Map (src); if (tgt != null) Console.WriteLine($"name = {tgt.name}"); } } public class source { public string name { get; set; } public int age { get; set; } public List strList { get; set; } public List classList { get; set; } } public class target { public string name { get; set; } public int age { get; set; } public List strList { get; set; } public List 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(cfg); this.defaultMapping (cfg); this.vestingMapping(cfg); }); } public static Dest Map (Src src) { if (instance != null) return AutoMapper.Mapper.Map (src); else throw new Exception("Automapper not initialized."); // TODO: 错误信息需集中定义。 } /// /// 提供默认的类型映射,双向映射,依据属性名称 /// ////// /// private void defaultMapping (IMapperConfigurationExpression cfg) { cfg.CreateMap (); cfg.CreateMap (); } private void departmentMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap () .ForMember(dest => dest.ParentDepartmentCode, options => options.MapFrom(src => string.IsNullOrWhiteSpace(src.ParentDepartmentCode) ? src.DepartmentCode : src.ParentDepartmentCode)); cfg.CreateMap () .ForMember(dest => dest.ParentDepartmentCode, options => options.MapFrom(src => src.ParentDepartmentCode)); } private void vestingMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap () .ForMember(dest => dest.VestingDate, options => options.ResolveUsing (src => this.convertDate(src.VestingDate).GetValueOrDefault())); } private void grantMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap () .ForMember(dest => dest.GrantDate, options => options.ResolveUsing (src => { return this.convertDate(src.GrantDate).GetValueOrDefault(); })) .ForMember(dest => dest.GrantType, options => options.ResolveUsing (src => this.convertGrantType(src.GrantType))) .ForMember(dest => dest.IsPerformanceBased, options => options.ResolveUsing (src => string.Equals(src.IsPerformanceBased, "Y", StringComparison.OrdinalIgnoreCase))); } private void reinstatementMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap () .ForMember(dest => dest.ReinstatementDate, options => options.ResolveUsing (src => this.convertDate(src.ReinstatementDate).GetValueOrDefault())) .ForMember(dest => dest.Type, options => options.UseValue (ReinstatementType.R)); } private void employeeMapping(IMapperConfigurationExpression cfg) { cfg.CreateMap () .ForMember(dest => dest.SAFEforSubsequentSalse, options => options.ResolveUsing (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(data);