Issue似乎条件被忽略了。这是我的场景:
源类
public class Source
{
public IEnumerable<Enum1> Prop1{ get; set; }
public IEnumerable<Enum2> Prop2{ get; set; }
public IEnumerable<Enum3> Prop3{ get; set; }
}
枚举是字节的子类,并用 [Flags] 装饰。目标类仅包含 Enum1、Enum2 和 Enum3 等属性,其中包含“总计”按位值。因此,本质上,如果枚举包含 Enum1.value!、Enum1.Value2 和 Enum1.Value3,则目标将包含 Enum1.Value1 | 的按位值。枚举1.值2 |枚举1.值3
目的地舱位
public Enum1 Prop1 { get; set; }
public Enum2 Prop2 { get; set; }
public Enum3 Prop3 { get; set; }
自动映射器映射
Mapper.CreateMap<Source, Destination>()
.ForMember(m => m.Prop1, o =>
{
o.Condition(c => !c.IsSourceValueNull);
o.MapFrom(f => f.Prop1.Aggregate((current, next) => current | next));
})
.ForMember(m => m.Prop2, o =>
{
o.Condition(c => !c.IsSourceValueNull);
o.MapFrom(f => f.Prop2.Aggregate((current, next) => current | next));
})
.ForMember(m => m.Prop3, o =>
{
o.Condition(c => !c.IsSourceValueNull);
o.MapFrom(f => f.Prop3.Aggregate((current, next) => current | next));
});
当内部属性不为空并且映射成功并正确设置目标时,映射工作正常。但是,我想在成员源值为null时跳过映射(当Prop1为null时,则跳过映射)。
我通过调试可以看到 Source.Prop1 为空。该条件被完全忽略并得到异常,表明该值为空。
Trying to map Source to Destination. Destination property: Prop1. Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. --> Value cannot be null. Parameter name: source
我不确定 IsSourceValueNull 是否检查 Prop1 或不为空的实际 Source 类。只有成员 Prop1 为空。
任何帮助表示赞赏。