2017-03-03 180 views
0

unflatten我有一个这样的例子: Automapper由前缀

class Fields 
{ 
    string ContactOneName{get;set;} 
    string ContactOnePhone{get;set;} 
    string ContactOneSpouseName{get;set;} 
    string ContactOneSpousePhone{get;set;} 
} 

而且我想映射到这样一个模型:

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

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

有许多领域和我不不想为每个字段写一个映射。 这可能吗? 如果是这样怎么样?

注意:这个问题几乎是AutoMapper unflattening complex objects of same type的重复,但我想要一个解决方案而不是手动映射所有东西,因为在这种情况下,它不值得使用automapper。

回答

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(); }); 
});