You need to conditionally display properties based on if they appear in the list InvalidProperties. If the current source source name exists in the list, it must use the value of the recipients.
Created a solution, but not sure if this should be done correctly:
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 );
}
Using:
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 );
Personal outputs:
- Age: 45 (instead of 55)
- FirstName: John
- LastName: Smith
Allergy:
- Allergy: Penacillin
- Id: 2 (instead of 1)
source
share