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

2 Answers 2

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.

2
  • 6
    I want to do trimming for all the members of the source object not for a single one. can u tell me how that is to be done? Commented Jan 24, 2015 at 6:58
  • You can refer to @Andrew Whitaker 's answer Commented May 1, 2021 at 8:52
7

You can also use AddTransform

CreateMap<DataViewModel, DataSource>()
    .AddTransform<string>(s => string.IsNullOrWhiteSpace(s) ? "" : s.Trim());

Not the answer you're looking for? Browse other questions tagged or ask your own question.