c# - 嵌套类中的 Automapper 映射成员

标签 c# automapper

我被 AutoMapper 语法困住了。

如何跳过嵌套类中的映射成员(条件字符串为空)? 我尝试了以下代码:

[TestMethod]
public void TestMethod4()
{
    var a = new A { Nested = new NestedA { V = 1, S = "A" } };
    var b = new B { Nested = new NestedB { V = 2, S = string.Empty } };

    Mapper.CreateMap<B, A>();   
    Mapper.CreateMap<NestedB, NestedA>().ForMember(s => s.S, opt => opt.Condition(src => !string.IsNullOrWhiteSpace(src.S)));
    var result = Mapper.Map(b, a);

      Assert.AreEqual(2, result.Nested.V);       // OK
      Assert.AreEqual("A", result.Nested.S);     // FAIL: S == null
}

谢谢

最佳答案

您是否尝试过使用建议的 opt.Skip here .

Mapper.CreateMap<NestedB, NestedA>()
 .ForMember(s => s.S, opt => opt.Skip(src => !string.IsNullOrWhiteSpace(src.S)));

编辑:

在深入挖掘源代码之后。我看到在 TypeMapObjectMapperRegistry 类(处理嵌套对象映射的类)中,它在查看是否需要保留目标值之前返回(使用 UseDestinationValue)。否则,我会建议这个:

Mapper.CreateMap<B, A>();
            Mapper.CreateMap<NestedB, NestedA>()
                .ForMember(s => s.S, opt => opt.Condition(src => !string.IsNullOrWhiteSpace(src.S)))
                .ForMember(s => s.S, opt => opt.UseDestinationValue());

我找到了 this吉米似乎在这里解决了核心问题。

因此,根据我的发现,似乎没有办法同时使用 Condition 和 UseDestinationValue。

关于c# - 嵌套类中的 Automapper 映射成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9105221/

相关文章:

c# - 如何在 ASP.NET GridView 中的 BoundField 上方添加一行

c# - DataGrid 不应该出现的重复数据

c# - 向 Automapper ForMember 添加额外参数的简单方法

c# - 如何从存储库中检索域对象

c# - 使用 AutoMapper 从数据库加载实体?

c# - 不通过调试器运行关键业务 C# 控制台应用程序的原因是什么?

c# - 使用 LINQ 获取嵌套列表的计数列表

c# - 使 Guid 属性线程安全

c# - 在 Azure 函数中初始化 AutoMapper

asp.net-core - 如何在 AutoMapper 配置文件类中注入(inject)服务