asp.net-mvcormautomapperdatamapperasp.net-mvc-5.1

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


Solution

  • 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.