需要根据属性是否出现在InvalidProperties
列表中有条件地映射属性。如果列表中存在当前源属性名称,则它应使用目标值。
创建了一个解决方案,但不确定这是否是“正确的方法”:
public class MyBassClass
{
public List<string> InvalidProperties
{
get;
set;
}
}
public class PersonAllergy : MyBassClass
{
public PersonAllergy()
{
InvalidProperties = new List<string>();
}
public int Id
{
get;
set;
}
public string Allergy
{
get;
set;
}
}
public class Person : MyBassClass
{
public Person()
{
InvalidProperties = new List<string>();
Allergy = new PersonAllergy();
}
public PersonAllergy Allergy
{
get;
set;
}
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public int Age
{
get;
set;
}
}
private static bool IgnoreInvalid( AutoMapper.ResolutionContext context )
{
return ( (MyBassClass)context.InstanceCache.First().Value )
.InvalidProperties.Contains( context.MemberName );
}
用法:
Person person = new Person();
person.FirstName = "john";
person.LastName = "smith";
person.Age = 45;
person.Allergy.Id = 1;
person.Allergy.Allergy = "Penacilin";
person.Allergy.InvalidProperties.Add( "Id" );
person.InvalidProperties.Add( "Age" );
Person templatePerson = new Person();
templatePerson.FirstName = "sam";
templatePerson.LastName = "rottenburg";
templatePerson.Age = 55;
templatePerson.Allergy.Id = 2;
templatePerson.Allergy.Allergy = "Monkeys";
AutoMapper.Mapper.CreateMap<Person, Person>()
.ForAllMembers( opt => opt.Condition( IgnoreInvalid ) );
AutoMapper.Mapper.CreateMap<PersonAllergy, PersonAllergy>()
.ForAllMembers( opt => opt.Condition( IgnoreInvalid ) );
var mergedPerson = AutoMapper.Mapper
.Map<Person, Person>(templatePerson, person);
mergedPerson.Allergy = AutoMapper.Mapper
.Map<PersonAllergy, PersonAllergy>( templatePerson.Allergy, person.Allergy );
人员输出:
过敏输出: