2017-09-26 19 views
2

有沒有辦法忽略映射空值到目的地全球(所有映射配置)?如何全局忽略映射源空值?

東西去這裏:

//Automapper config 
    Mapper.Initialize(cfg => 
    { 
     //Initializes all mapping profiles in the assembly 
     cfg.AddProfiles(Assembly.GetExecutingAssembly().GetName().Name); 

     //If map is called without a profile creates default map 
     cfg.CreateMissingTypeMaps = true; 
    }); 

這是實例映射。這是我想要完成的一個例子。

//Models 
    class User { 
     public string Name {get; set;} 
     public string Email {get; set;} 
     public string Password {get; set;} 
    } 

    class UserDto { 
     public string Name {get; set;} 
     public string Email {get; set;} 
    } 

//Start instances 
    var user = new User { Name = "John", Email = "[email protected]", Password = "123"}; 

    var userDto = new UserDto { Name = "Tim" }; 
//Notice that we left the Email null on the DTO 


//Mapping 
    Mapper.Map(userDto, user); 

結果以用戶收到空郵件結束。除非源(userDto)上提供了新電子郵件,否則我希望不更改用戶電子郵件。在忽略來自重寫目的地(用戶)

UPDATE在源對象上的所有類型的所有空屬性換句話說:的答案都不低於解決問題。他們根本不適合收藏。雖然Autommaper計算出這個錯誤,我能夠通過使用ExpandoObject來解決我的問題,以篩選出如下映射之前的所有空屬性:

var patchInput = new ExpandoObject() as IDictionary<string, object>; 

foreach (var property in userDto.GetType().GetProperties()) 
    if (property.GetValue(userDto) is var propertyValue && propertyValue != null) 
     patchInput.Add(property.Name, propertyValue); 

Mapper.Map(patchInput, user); 
+1

的可能的複製[自動映射器跳過空值與自定義解析器](https://stackoverflow.com/questions/20021633/automapper-skip-null-values-with-custom-resolver) – xenteros

+0

你可以請添加一個例子? – Valerii

+1

@Valerii添加配置應該在上面的部分。不知道如果那是你想要的。 – DonO

回答

1

它應該工作

Mapper.Initialize(cfg => 
     { 
      cfg.AddProfiles(Assembly.GetExecutingAssembly().GetName().Name); 
      cfg.CreateMissingTypeMaps = true; 
      cfg.ForAllMaps((typeMap, map) => 
       map.ForAllMembers(option => option.Condition((source, destination, sourceMember) => sourceMember != null))); 
     }); 
+0

這回答了我的問題,但似乎在各個映射配置文件上定義的其他條件不再有效。 :\ – DonO

+0

這不適用於數字或空集合 – DonO

+1

@DonO它適用於類似於int?的Nulable數字,對於像int這樣的值類型,它不起作用,因爲值不能爲空。 – Valerii