如何全局忽略映射源null值?

时间:2017-09-26 14:03:23

标签: c# automapper

有没有办法忽略将空值映射到目标全局(对于所有映射配置)?

这里有一些东西:

//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 = "john@live.com", Password = "123"};

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


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

这是例如映射。这是我想要完成的一个例子。

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);

结果最终是用户拥有空电子邮件。我希望除非在源(userDto)上提供新电子邮件,否则不会更改用户电子邮件。换句话说,忽略源对象上所有类型的所有空属性来覆盖目标(用户)

更新:以下答案均未解决问题。他们根本不适合收藏。当Autommaper发现这个错误时,我能够通过使用ExpandoObject在映射之前过滤掉所有null属性来解决我的问题,如下所示:

{{1}}

1 个答案:

答案 0 :(得分: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)));
        });