Automapper 的条件被忽略

标签 automapper

问题
似乎条件被忽略了。这是我的场景:

源类

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

任何帮助表示赞赏。

最佳答案

我认为你需要做 ConditionMapFrom分两步:

.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/

相关文章:

c# - 向 AutoFixture 提供真实的 AutoMapper 实例

c# - 使用自动映射器时无法从 'System.Collections.Generic.IEnumerable<x>' 转换为 'x'

c# - C# 中的自动映射器错误。...的最佳重载匹配有一些无效参数

c# - 如何使用自动映射器跳过对象

c# - 在使用 Automapper 映射 ViewModel 之后,我应该如何测试以及应该测试什么?

c# - 将不相关的集合映射到一个集合

c# - .Net Core Automapper 缺少类型映射配置或不受支持的映射

.net - AutoMapper 的替代品

c# - 如何将 Automapper 与 Autofac 一起使用

c# - 使用 AutoMapper 映射未知类型