问题 看起来像条件被忽略。这是我的情景:自动映射器的状态被忽略
源类
public class Source
{
public IEnumerable<Enum1> Prop1{ get; set; }
public IEnumerable<Enum2> Prop2{ get; set; }
public IEnumerable<Enum3> Prop3{ get; set; }
}
从一个字节的枚举子类,然后用[标志]装饰。目标类只包含Enum1,Enum2和Enum3等属性,包含“总”位值。所以在本质上,如果Enumeration包含Enum1.value!,Enum1.Value2和Enum1.Value3,则目标将包含Enum1.Value1 | Enum1.Value2 |当内属性非空值和映射成功和正确地设定目的地Enum1.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为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类不是null。只有成员Prop1为空。
任何帮助isappreciated。
谢谢帕特里克。通过分离出来,我可以得到完全相同的例外。 – TimJohnson
我以为我以前做过。一种可能的情况是,c.IsSourceValueNull可能表示整个要映射的源对象是否为空。我想知道它应该是“c => c.Prop1!= null”? – PatrickSteele
使用“条件”找不到代码示例。抱歉。我想你总是可以这样做:o.MapFrom(f => f.Prop1 == null?null:f.Prop1.Aggregate(...)) – PatrickSteele