自动映射器的条件被忽略

2024-02-23

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 为空。

任何帮助表示赞赏。


我认为你需要做Condition and MapFrom分两步:

.ForMember(c => c.Prop1, o => o.Condition(c => !c.IsSourceValueNull));
.ForMember(c => c.Prop1, o => o.MapFrom(f => f.Prop1.Aggregate(...));

如果 Condition 的计算结果为 false,则永远不会使用 MapFrom。

EDIT

嗯...这似乎不起作用。我以为我以前在某个地方用过它。您可以仅使用 MapFrom:

.MapFrom(f => f.Prop1 == null ? null : f.Prop1.Aggregate(...));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自动映射器的条件被忽略 的相关文章

随机推荐