这是我尝试过的。无法确定如何实现
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();
}