我有一个带有子属性的类:
Person {
string Name;
Address Address {
string Street;
}
}
当我构造新的Person对象时,我希望automapper执行如下操作:
var person = new Person();
person.Name = sourcePerson.Name;
person.Address = new Address();
person.Address.Street = sourcePerson.Address.Street;
但是如果我已经有了一个Person对象,我只想填充它,如果我的Person对象已经有了Address set,我希望Address对象被填充以及不已被替换。基本上:
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.
理想情况下,我希望能够配置AutoMapper以自动计算出来,即如果Address不为null - 然后创建并设置它,如果它不为null - 那么只需更新它。
现在我按如下方式使用AfterMap:
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
});
我这样做是因为Address
对象是一个自我跟踪实体,它有一个我无法覆盖的状态。
有没有办法重构我的代码以不使用AfterMap?