4
Mapper.CreateMap<DataViewModel, DataSource>()

My Source Here Contains String Values Coming from user interface. I want to trim all the string before i map it to my destination object. Couldn't find a solution for this. Anyone Knows how this is to be done

Koushik Saha
  • 673
  • 1
  • 10
  • 25

2 Answers2

9

This can be done using the ForMember method, like so:

Mapper.CreateMap<DataViewModel, DataSource>()
.ForMember(x => x.YourString, opt => opt.MapFrom(y => y.YourString.Trim()));

If you want to trim more than one property you can chain the .ForMember() method like this:

Mapper.CreateMap<DataViewModel, DataSource>()
.ForMember(x => x.YourString, opt => opt.MapFrom(y => y.YourString.Trim()))
.ForMember(x => x.YourString1, opt => opt.MapFrom(y => y.YourString1.Trim()))
.ForMember(x => x.YourString2, opt => opt.MapFrom(y => y.YourString2.Trim()));

Whilst this would get the job done, I would suggest performing input sanitisation elsewhere in your application as it doesn't belong in the mapping.

Joseph Woodward
  • 9,191
  • 5
  • 44
  • 63
6

You can also use AddTransform

CreateMap<DataViewModel, DataSource>()
    .AddTransform<string>(s => string.IsNullOrWhiteSpace(s) ? "" : s.Trim());
Mohammad Dayyan
  • 21,578
  • 41
  • 164
  • 232