Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper null string to empty

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?

like image 250
Shawn Mclean Avatar asked Oct 03 '11 22:10

Shawn Mclean


1 Answers

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());
        ...
    }
}
like image 147
David Wick Avatar answered Oct 14 '22 05:10

David Wick