简体   繁体   English

嵌套类中的Automapper Map成员

[英]Automapper Map Members in the nested class

Im get stuck with AutoMapper syntax. 我陷入了AutoMapper语法。

How to skip mapping members in the nested class (by condition string is empty)? 如何跳过嵌套类中的映射成员(条件字符串为空)? Im tried following code: 我试过以下代码:

[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
}

Thanks 谢谢

Have you tried using the opt.Skip suggested here . 您是否尝试过使用opt.Skip建议在这里

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

EDIT: 编辑:

After some digging in the source. 经过一些挖掘源头。 I see that in the TypeMapObjectMapperRegistry class (the one that handles mappings for nested objects) it returns before seeing if the the destination value is needed to be preserved (using UseDestinationValue). 我在TypeMapObjectMapperRegistry类(处理嵌套对象的映射的类)中看到它返回,然后查看是否需要保留目标值(使用UseDestinationValue)。 Otherwise, I was going to suggest this: 否则,我会建议:

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());

I found this where Jimmy seems to address the core issue here. 我发现这个地方吉米似乎在这里讨论的核心问题。

So, from what I've found, there doesn't seem to be a way to use Condition and UseDestinationValue at the same time. 因此,根据我的发现,似乎没有办法同时使用Condition和UseDestinationValue。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM