Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim String In Automapper

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

like image 363
Koushik Saha Avatar asked Nov 14 '25 22:11

Koushik Saha


1 Answers

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.

like image 128
Joseph Woodward Avatar answered Nov 17 '25 18:11

Joseph Woodward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!