在处理包含派生类集合的对象时,我遇到了 AutoMapper 2.1.267.0 的问题。我使用以下类在更简单的场景中隔离了我的问题:
public class ClassABase
{
public string Name { get; set; }
}
public class ClassA : ClassABase
{
public string Description { get; set; }
}
public class ClassBBase
{
public string Title { get; set; }
}
public class ClassB : ClassBBase
{
public string Text { get; set; }
}
public class ContainerA
{
public IList<ClassA> ClassAList { get; set; }
public ClassA ClassA { get; set; }
}
public class ContainerB
{
public IList<ClassB> ClassBList { get; set; }
public ClassB ClassB { get; set; }
}
和这些映射
public class ClassABaseToClassBBase : Profile
{
protected override void Configure()
{
CreateMap<ClassABase, ClassBBase>()
.Include<ClassA, ClassB>()
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Name));
Mapper.AssertConfigurationIsValid();
}
}
public class ClassAToClassB : Profile
{
protected override void Configure()
{
CreateMap<ClassA, ClassB>()
.ForMember(dest => dest.Text, opt => opt.MapFrom(src => src.Description));
Mapper.AssertConfigurationIsValid();
}
}
public class ContainerAToContainerB : Profile
{
protected override void Configure()
{
CreateMap<ContainerA, ContainerB>()
.ForMember(dest => dest.ClassBList,
opt => opt.MapFrom(src => Mapper.Map<IList<ClassA>, IList<ClassB>>(src.ClassAList)))
.ForMember(dest => dest.ClassB, opt => opt.MapFrom(src => src.ClassA));
}
}
这里是初始化
Mapper.Initialize(x =>
{
x.AddProfile<ClassABaseToClassBBase>();
x.AddProfile<ClassAToClassB>();
x.AddProfile<ContainerAToContainerB>();
});
和一个总结一切的图表(红色箭头代表 AutoMapper 映射)
我已将 ContainerA 实例映射到 ContainerB。第一种情况可以正常工作。目标对象已完全填充,如下图所示:
但是如果我添加这个映射
public class ClassBBaseToClassB : Profile
{
protected override void Configure()
{
CreateMap<ClassBBase, ClassB>()
.ForMember(dest => dest.Text, opt => opt.Ignore());
Mapper.AssertConfigurationIsValid();
}
}
Mapper.Initialize(x =>
{
x.AddProfile<ClassABaseToClassBBase>();
x.AddProfile<ClassAToClassB>();
x.AddProfile<ClassBBaseToClassB>();
x.AddProfile<ContainerAToContainerB>();
});
结果是
集合的所有元素的“文本”属性变为空。正如您在图像中看到的,containerB.ClassB 对象的“Text”属性仍然被正确映射。这只发生在集合中。我不知道发生了什么。有什么线索吗?
谢谢