Auto empty string for empty

When I try to map an object to a null string property, the assignment is also null. Are there any global settings that I can enable by saying that the entire empty string should be displayed empty?

+10
asp.net-mvc asp.net-mvc-3 automapper
Oct 03 '11 at 10:16
source share
3 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()); ... } } 
+21
Oct 03 2018-11-11T00:
source share

Like David Wieck, you can also use ConvertUsing with a lambda expression, which eliminates the need for an extra class.

 Mapper.CreateMap<string, string>().ConvertUsing(s => s ?? string.Empty); 
+10
Apr 15 '14 at 14:08
source share

If you need a non-global setting and want to do this for each property:

 Mapper.CreateMap<X, Y>() .ForMember( dest => dest.FieldA, opt => opt.NullSubstitute(string.Empty) ); 
+8
May 10 '13 at 6:18
source share



All Articles