代码之家  ›  专栏  ›  技术社区  ›  Bellash

通用自动映射配置文件注册

  •  0
  • Bellash  · 技术社区  · 7 年前

    这是我尝试过的。无法确定如何实现 HasProperty .[prop]

    public class Person
    {
       public string ID{get;set;}
       public string Name{get;set;}
       public DateTime Birth{get;set;}
    
       public class _Profile:AutoMapper.Profile{
         public _Profile(){
           /*traditional way*/
            CreateMap<Person, PersonDTO>()
            .ForMember(dest => dest.ID, opt => opt.MapFrom(src => src.ID))
             /*omitted for brevity*/
            .ReverseMap();
               /*  Generic way*/
                BaseModelMappingConfigurator
                .RegisterBaseModelMap(CreateMap<Person, PersonDTO>,true);
         }
       }
    }
    

    RegisterBaseModelMap 方法实现

         public static void RegisterBaseModelMap<TSource, TDestination>
                  (Func<IMappingExpression<TSource, TDestination>> createMap, 
         bool reverse = true)
        {
            var mapCreator = createMap();
            var properties = typeof(TSource)
         .GetProperties(System.Reflection.BindingFlags.Public | 
                           System.Reflection.BindingFlags.DeclaredOnly);
         foreach (var prop in properties)
            {
                if (typeof(TDestination).HasProperty(prop))
                {
                    mapCreator.ForMember(dest => dest.[prop], 
                    opt => opt.MapFrom(src => src.[prop]));
                }
            }
            if (reverse) mapCreator.ReverseMap();
        }
    
    0 回复  |  直到 7 年前