我有一个这样的例子:
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 :(得分: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(); });
});