Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper to apply common/global formatter on all fields?

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?

like image 714
Raymond Avatar asked Jun 22 '15 18:06

Raymond


1 Answers

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.

like image 134
Andrew Whitaker Avatar answered Sep 22 '22 15:09

Andrew Whitaker