AutoMapper - map all nulls to empty strings

68 views Asked by At

For compatibility reasons I need to map, ideally with the AutoMapper, some source POCO, that can contain different nullable properties like DateTime?, bool? or whatever else (because in the source application there is ternary logic) but for the DTO I need all of them to be mapped to an object with the same set of properties, where all of them are just strings. And null values need to be replaced with empty strings.

Then it means I need like:

Source: TerminationDate DateTime? ... null

Destination: TerminationDate string ... ""

I would need to do it for all properties, for all nullable types. I have not found any suitable way how to configure the AutoMapper to do that without a need to go through all the properties one by one (what I want to avoid since the names perfectly match). I know could do a global map as CreateMap<string,string>().Convert..(....) but it would corrupt all other mappings where the null -> null mapping is legitimate.

I am looking for something like:

mapper.CreateMap<Source,Destination>().ForAllMembersMappingBetweenTypes<DateTime?,string>(UseTheConversion)

Perhaps I may build the expression using reflection, but this looks a bit heavy.

1

There are 1 answers

0
Lucian Bargaoanu On

The easiest way is to do it globally, for all Nullables.

    cfg.CreateMap(typeof(Nullable<>), typeof(string)).ConvertUsing(s => s == null ? "" : s.ToString());

You could even write a generic type converter to avoid the boxing.

If you want it just for that particular map, you need ForAllMembers to apply a converter for each property pair, Nullable to string. That's messy. You'd need to compare that with doing it by hand, is it really an improvement?