2017-03-03 4 views
0

에 의해 패턴 화 해제Automapper 내가이 같은 예를 접두사

class Contacts 
{ 
    Contact ContactOne {get;set;} 
    Contact ContactOneSpouse {get;set;} 
} 

class Contact 
{ 
    string Name {get;set;} 
    string Phone {get;set;} 
} 

이 필드를 많이하고 내가 돈 ' 각 필드에 대한 매핑을 쓰고 싶지 않습니다. 이것이 가능합니까? 그렇다면 어떻게?

NB :이 질문은 거의 AutoMapper unflattening complex objects of same type의 복제본입니다. 그러나이 경우 자동 매핑을 사용하지 않는 것이 좋기 때문에 모든 것을 수동으로 매핑하지 않는 솔루션이 필요합니다.

답변

0

당신은 this을하고 추가 할 수 있습니다 다음과 같이

public static IMappingExpression<TSource, TDestination> ForAllMembers<TSource, TDestination, TMember>(
    this IMappingExpression<TSource, TDestination> mapping, 
    Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> opt) 
{ 
    var memberType = typeof(TMember); 
    var destinationType = typeof(TDestination); 

    foreach(var prop in destinationType.GetProperties().Where(prop => prop.PropertyType.Equals(memberType))) 
    { 
     var parameter = Expression.Parameter(destinationType); 
     var destinationMember = Expression.Lambda<Func<TDestination, TMember>>(Expression.Property(parameter, prop), parameter); 

     mapping.ForMember(destinationMember, opt); 
    } 

    return mapping; 
} 

는 그런 다음 매핑을 구성 할 수 있습니다

var config = new MapperConfiguration(cfg => 
{ 
    cfg.CreateMap<Fields, Contacts>().ForAllMembers<Fields, Contacts, Contact>(x => { x.Unflatten(); }); 
});