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?
If you truly want to apply these rules to all strings, you can set up a mapping from
string
tostring
:This rule will be picked up when mapping from one
string
property to another.