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