过去几天我一直在努力解决 Automapper 的奇怪行为。我的AutoMapper版本是10.1.1;目前我无法访问 .NET Standard 2.1,因此无法升级到 12.0.1。
涉及的类的关系如下所示:
//On the From side:
class FromA {
// ...stuff...
public FromB MemberB { get; set; }
// ...stuff...
}
class FromB {
// ...stuff...
}
//On the To side:
class ToA {
// ...stuff...
public ToB MemberB { get; set; }
// ...stuff...
}
class ToB {
// ...stuff...
public ICollection<ToC> MemberC { get; set; }
// ...stuff...
}
class ToC {
// ...stuff...
}
然后在映射配置方面,我们有:
//I've got the following support member value resolver:
internal class TypeMappingMemberValueResolver<TSource, TDestination, TSourceMember, TDestinationMember>
: IMemberValueResolver<TSource, TDestination, TSourceMember, TDestinationMember>
{
public TDestinationMember Resolve(TSource source, TDestination destination, TSourceMember sourceMember, TDestinationMember destMember, ResolutionContext context)
{
return context.Mapper.Map<TSourceMember, TDestinationMember>(sourceMember, destMember);
}
}
//Then, inside Profiles:
CreateMap<FromA, ToA>()
...
.ForMember(to => to.MemberB, opt => opt.MapFrom(new TypeMappingMmeberValueResolver<FromA, ToA, FromB, ToB>(src => src.MemberB)
...
//Here, I'm just trying to be explicit that MemberB should be mapped according to another registered map. It might be possible to do this implicitly, but I'm uncertain how.
// Regardless, my remaining map:
CreateMap<FromB, ToB>()
...
.ForMember(to => to.MemberC, opt => opt.Ignore())
鉴于此,当我执行时:
Mapper.Map<FromA, ToA>(instanceOfFromA, instanceOfToA);
instanceOfToA 的 MemberC 属性现在将设置为空数组。我在 FromB -> ToB 映射中还有许多其他被 Ignored() 的属性,并且这些属性都工作正常。
我的期望是,instanceOfA.MemberB.MemberC 不会受到影响,特别是不会被更改或删除其数据。
其他一些不应该成为因素的事情:
我尝试了许多其他事情,并得到了一些发现:
我一直在努力解决集合被清除而不是映射的问题。这可能与
问题中的场景有关。
该问题的公认答案