问题 似乎条件被忽略了.这是我的场景:
来源类
public class Source
{
public IEnumerable<Enum1> Prop1{ get; set; }
public IEnumerable<Enum2> Prop2{ get; set; }
public IEnumerable<Enum3> Prop3{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
enums是一个字节的子类,用[Flags]修饰.目标类只包含Enum1,Enum2和Enum3等属性,其中包含"total"按位值.因此,如果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; }
Run Code Online (Sandbox Code Playgroud)
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));
});
Run Code Online (Sandbox Code Playgroud)
当内部属性不为null并且映射成功并正确设置目标时,映射工作正常.但是,我想在成员源值为null时跳过映射(当Prop1为null时,然后跳过映射).
我可以从调试中看到Source.Prop1为null.条件被完全忽略并获得异常,表示该值为null.
Trying to map Source to Destination. Destination property: Prop1. Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. --> Value cannot be null. Parameter name: source
Run Code Online (Sandbox Code Playgroud)
我不确定IsSourceValueNull是否检查Prop1或实际的Source类是否为null.只有成员Prop1为空.
任何帮助都会得到赞赏.
我认为你需要做的Condition,并MapFrom在两个步骤:
.ForMember(c => c.Prop1, o => o.Condition(c => !c.IsSourceValueNull));
.ForMember(c => c.Prop1, o => o.MapFrom(f => f.Prop1.Aggregate(...));
Run Code Online (Sandbox Code Playgroud)
如果Condition计算结果为false,则永远不会使用MapFrom.
编辑
嗯......这似乎不起作用.我以为我曾经在某个地方使用过它.你可以只使用MapFrom:
.MapFrom(f => f.Prop1 == null ? null : f.Prop1.Aggregate(...));
Run Code Online (Sandbox Code Playgroud)