AutoMapper to apply common/global formatter on all fields?

4.4k views Asked by At

I am using AutoMapper 3.2.1

I just got a requirement where the consumers of my project want me to do some simple transformations -- have all string fields trimmed of whitespace and convert null to string.empty.

How would I do this in AutoMapper in an efficient manner?

e.g.

public class Person()
{
   public string First {get; set;}
   public string Middle {get; set; }
   public string Last {get; set; }
   public DateTime DateOfBirth {get; set; }
}

public class PersonDto()
{
   public string First {get; set;}
   public string Second {get; set; }
   public string Last {get; set; }
   public DateTime DateOfBirth {get; set; }
}

And my map example:

Mapper.CreateMap<Person, PersonDto>().
    .ForMember(dst => dst.Second, opt => opt.MapFrom(src => src.Middle));

Mapper.CreateMap<PersonDto, Person>().
    .ForMember(dst => dst.Last, opt => opt.MapFrom(src => src.Second));

I tried google to find an answer, saw that some people were using:

Mapper.ForSourceType<string>().AddFormatter(MyCustomStringFormatter)

but it seems AddFormatter is obsolete?

2

There are 2 answers

1
Andrew Whitaker On BEST ANSWER

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.

0
Kool On

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);
                }
            }
        }