Automapper null string to empty

和自甴很熟 提交于 2019-12-08 15:20:43

问题


When I try to map an object that has a null string property, the destination is also null. Is there a global settings I can turn on that says all null string should be mapped to empty?


回答1:


Something like this should work:

public class NullStringConverter : ITypeConverter<string, string>
  {
    public string Convert(string source)
    {
      return source ?? string.Empty;
    }
  }

And in your configuration class:

public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.CreateMap<string, string>().ConvertUsing<NullStringConverter>();

        Mapper.AddProfile(new SomeViewModelMapper());
        Mapper.AddProfile(new SomeOtherViewModelMapper());
        ...
    }
}



回答2:


If you need a non-global setting, and want to do it per property:

Mapper.CreateMap<X, Y>()
.ForMember(
    dest => dest.FieldA,
    opt => opt.NullSubstitute(string.Empty)
);



回答3:


Similar to David Wick's answer, you can also use ConvertUsing with a lambda expression, which eliminates the requirement for an additional class.

Mapper.CreateMap<string, string>().ConvertUsing(s => s ?? string.Empty);


来源:https://stackoverflow.com/questions/7641298/automapper-null-string-to-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!