我有一个带有子属性的类:
Person {
string Name;
Address Address {
string Street;
}
}
当我构造新的 Person 对象时,我希望自动映射器执行如下操作:
var person = new Person();
person.Name = sourcePerson.Name;
person.Address = new Address();
person.Address.Street = sourcePerson.Address.Street;
但是如果我已经有一个 Person 对象,我只想填充它,并且如果我的 Person 对象已经设置了 Address ,我希望该 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
object 是一个自我跟踪实体,并且它具有我无法覆盖的状态。
有没有办法重构我的代码以不使用 AfterMap?