16

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?

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

3 Answers3

26

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());
        ...
    }
}
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
David Wick
  • 7,055
  • 2
  • 36
  • 38
19

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)
);
Nick Josevski
  • 4,156
  • 3
  • 43
  • 63
14

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);
Joe
  • 7,113
  • 1
  • 29
  • 34