I have a class with a child property:
Person {
string Name;
Address Address {
string Street;
}
}
When I construct new Person object, I want automapper to execute something like:
var person = new Person();
person.Name = sourcePerson.Name;
person.Address = new Address();
person.Address.Street = sourcePerson.Address.Street;
but if I already have a Person object, I just want to fill it, and if my Person object already has Address set, to I want that Address object to be filled as well, not replaced. Essentially:
var person = GetExistingPerson();
...
Mapper.Map(sourcePerson, person); // this will fill person object
// here is what it does now (internally):
person.Name = sourcePerson.Name;
person.Address = new Address();
person.Address.Street = sourcePerson.Address.Street; // <-- not what I want
// here is what I do want to happen:
person.Name = sourcePerson.Name;
person.Address.Street = sourcePerson.Address.Street; // i.e. not override Address, but fill it.
Ideally I want to be able to configure AutoMapper to figure this out automatically, i.e. if Address is not null - then create and set it, if it is not null - then just update it.
Right now I use AfterMap as follows:
var map = Mapper.Create<SourcePerson, Person>();
map.ForSource(src=>src.Name,opt=>opt.MapFrom(dst=>dst.Name));
map.AfterMap((srcPerson, dstPerson) => {
if (dstPerson.Address == null) dstPerson.Address = Mapper.Map<Address>(srcPerson.Address); // set
else Mapper.Map(srcPerson.Address, dstPerson.Address); // fill
});
I do this because Address
object is a self tracking entity and it has a state that I can not override.
Is there a way to refactor my code to not use AfterMap?