C# 自动映射嵌套类中的成员

C# 自动映射嵌套类中的成员,c#,automapper,C#,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,

我被自动映射语法卡住了

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

[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
}
[TestMethod]
公共void TestMethod4()
{
var a=newa{Nested=newnesteda{V=1,S=“a”};
var b=new b{Nested=new NestedB{V=2,S=string.Empty};
CreateMap();
Mapper.CreateMap().FormMember(s=>s.s,opt=>opt.Condition(src=>!string.IsNullOrWhiteSpace(src.s));
var result=Mapper.Map(b,a);
Assert.AreEqual(2,result.Nested.V);//确定
Assert.AreEqual(“A”,result.Nested.S);//失败:S==null
}

谢谢

您是否尝试过使用建议的选项跳过

Mapper.CreateMap()
.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());
Mapper.CreateMap();
Mapper.CreateMap()
.ForMember(s=>s.s,opt=>opt.Condition(src=>!string.IsNullOrWhiteSpace(src.s)))
.ForMember(s=>s.s,opt=>opt.UseDestinationValue());
我发现吉米似乎在这里解决了核心问题


因此,从我发现的情况来看,似乎没有一种方法可以同时使用Condition和UseDestinationValue。

Im使用AutoMapper v2,并且没有跳过选项。
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());