问题
似乎条件被忽略了。这是我的场景:
源类
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 等属性。因此,本质上如果 Enumeration 包含 Enum1.value!、Enum1.Value2 和 Enum1.Value3,则目标将包含 Enum1.Value1 | 的按位值。 Enum1.Value2 |枚举1.Value3
目的地类
public Enum1 Prop1 { get; set; }
public Enum2 Prop2 { get; set; }
public Enum3 Prop3 { get; set; }
AutoMapper 映射
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));
});
当内部属性不为空并且映射成功并正确设置目的地时,映射工作正常。但是,我想在成员源值为空时跳过映射(当 Prop1 为空时,则跳过映射)。
从调试中可以看出 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 为空。
任何帮助表示赞赏。
最佳答案
我认为你需要做 Condition
和 MapFrom
分两步:
.ForMember(c => c.Prop1, o => o.Condition(c => !c.IsSourceValueNull));
.ForMember(c => c.Prop1, o => o.MapFrom(f => f.Prop1.Aggregate(...));
如果条件评估为假,则永远不会使用 MapFrom。
编辑
嗯...这似乎行不通。我以为我以前在某个地方使用过它。您可以仅使用 MapFrom:
.MapFrom(f => f.Prop1 == null ? null : f.Prop1.Aggregate(...));
关于Automapper 的条件被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8012725/