2012-09-14 33 views
3

我想設置遵循以下規則的自動映射器映射。如果沒有使用目標對象,有條件地覆蓋目標

  • 如果未使用「就地」目的地語法,如果對象被傳遞在特定成員映射到值
  • ,然後使用目的地值

我已經試過這是我能想到的每一種方式。類似這樣的:

Mapper.CreateMap<A, B>() 
    .ForMember(dest => dest.RowCreatedDateTime, opt => { 
     opt.Condition(dest => dest.DestinationValue == null); 
     opt.UseValue(DateTime.Now); 
    }); 

這總是映射值。基本上我想要的是:

c = Mapper.Map<A, B>(a, b); // does not overwrite the existing b.RowCreatedDateTime 
c = Mapper.Map<B>(a);  // uses DateTime.Now for c.RowCreatedDateTime 

注意:A不包含RowCreatedDateTime。

我在這裏有什麼選擇?這很令人沮喪,因爲似乎沒有關於Condition方法的文檔,並且所有google結果似乎都集中在源值爲null的位置,而不是目的地。

編輯:

感謝帕特里克,他讓我在正確的軌道上..

我想出了一個解決方案。如果有人有更好的方式做到這一點,請讓我知道。注意我必須參考dest.Parent.DestinationValue而不是dest.DestinationValue。由於某種原因,dest.DestinationValue始終爲空。

.ForMember(d => d.RowCreatedDateTime, o => o.Condition(d => dest.Parent.DestinationValue != null)) 
.ForMember(d => d.RowCreatedDateTime, o => o.UseValue(DateTime.Now)) 

回答

4

我相信你需要設置兩個映射:一個與Condition(其確定的映射應執行)和一個定義該怎麼做,如果Condition返回true。類似這樣的:

.ForMember(d => d.RowCreatedDateTime, o => o.Condition(d => d.DestinationValue == null); 
.ForMember(d => d.RowCreatedDateTime, o => o.UseValue(DateTime.Now)); 
+0

不幸的是,這是行不通的。它每次都會覆蓋傳入的值。 –

+0

事實證明,你必須引用parent.DestinationValue,但我已經upvoted反正。 –

+0

有趣......感謝upvote! – PatrickSteele

相關問題