有沒有辦法忽略映射空值到目的地全球(所有映射配置)?如何全局忽略映射源空值?
東西去這裏:
//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);
的可能的複製[自動映射器跳過空值與自定義解析器](https://stackoverflow.com/questions/20021633/automapper-skip-null-values-with-custom-resolver) – xenteros
你可以請添加一個例子? – Valerii
@Valerii添加配置應該在上面的部分。不知道如果那是你想要的。 – DonO