2017-09-07 88 views
3

我使用AutoMapper將ViewModel映射到模型。但是,如果相應的源屬性爲null,我希望屬性不會映射。AutoMapper - 跳過映射空屬性

我的源類如下:

public class Source 
{ 
    //Other fields... 
    public string Id { get; set; } //This should not be mapped if null 
} 

和目的地類是:

public class Destination 
{ 
    //Other fields... 
    public Guid Id { get; set; } 
} 

這裏是我如何配置的映射:

Mapper.Initialize(cfg => 
{ 
    //Other mappings... 
    cfg.CreateMap<Source, Destination>() 
     .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null)); 
}); 

我認爲映射將意味着如果源代碼是,則屬性不會在目標中被覆蓋。但顯然我錯了:即使Source.Id爲空,它仍然被映射,AutoMapper爲它分配一個空Guid(00000000-0000-0000-0000-000000000000),覆蓋現有的。如果源代碼爲空,我該如何正確地告訴AutoMapper跳過屬性的映射?

注意:我不認爲這是Guid<->String轉換的問題,這種轉換工作在automapper中,我用它在pass中。問題在於它不會在Id屬性爲空時跳過它。

回答

4

簡單的方法是不必區分null和Guid.Empty。像這樣

cfg.CreateMap<Source, Destination>() 
     .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => ((Guid)srcMember) != Guid.Empty)); 

在這種情況下,源成員不是字符串值,你從地圖中,它的解析值將被分配給目標。它的類型是Guid,一個結構,所以它永遠不會爲空。一個空字符串將映射到Guid.Empty。見here

+0

嗯......我會試試看,但我不明白爲什麼這應該工作,如果我的不...我的意思是,如果srcMember爲null您的表達將返回false ...與我的相同「srcMember!= null」檢查相同的情況。爲什麼你的工作,如果我的不? –

+1

我已經添加了解釋。 –