asp.net-mvcasp.net-mvc-3automapper

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?


Solution

  • 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());
            ...
        }
    }