AutoMapper to apply common/global formatter on all fields?
In my case i looked around for solution where I can Trim all string props. Not for all existing Map definitions, BUT only in some of specific map definitions. My solution:
CreateMap<Source, Destination>()
// custom map settings...
.ForMember(x => x.Phone, opt => opt.Ignore())
//Trim all string props now...
.AfterMap<TrimAllStringProperty>();
private class TrimAllStringProperty : IMappingAction<object, object>
{
public void Process(object source, object destination)
{
var stringProperties = destination.GetType().GetProperties().Where(p => p.PropertyType == typeof(string));
foreach (var stringProperty in stringProperties)
{
string currentValue = (string)stringProperty.GetValue(destination, null);
if (currentValue != null)
stringProperty.SetValue(destination, currentValue.Trim(), null);
}
}
}
If you truly want to apply these rules to all strings, you can set up a mapping from string
to string
:
Mapper.CreateMap<string, string>()
.ConvertUsing(str => (str ?? "").Trim());
This rule will be picked up when mapping from one string
property to another.