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?
Asked
Active
Viewed 1.6k times
3 Answers
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
-
1What is: `Mapper.AddProfile(new SomeViewModelMapper());`? Is this something where I can add multiple mappers? – Shawn Mclean Oct 03 '11 at 23:15
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