【问题标题】:Automapper Map Members in the nested class嵌套类中的 Automapper 映射成员
【发布时间】:2012-02-03 00:20:55
【问题描述】:

我被 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
}

谢谢

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    您是否尝试过使用 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,Jimmy 似乎在这里解决了核心问题。

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

    【讨论】:

    • 我正在使用 AutoMapper v2,并且没有跳过选项。
    猜你喜欢
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多