2012-02-01 87 views
3

Im被AutoMapper語法卡住了。Automapper Map嵌套類中的成員

如何跳過嵌套類中的映射成員(通過條件字符串爲空)? 林嘗試下面的代碼:

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

感謝

回答

2

您是否嘗試過使用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。

+0

即時通訊使用AutoMapper v2,並沒有跳過選項。 – user1183964 2012-02-02 10:28:54