Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: map List<string> to List<Class>

Tags:

automapper

How can I map a List<string> to List<Class>?

Usecase: from the Webservice I'm getting a class with a list of string but in my MVC Viewmodel, I want to have Class instead with a single property, which has the value of the string. That way I can add Validation attributes to the property.

I have the way how I convert the List into a List, however I can't get the other way around to work.

Any simple solutions?

like image 712
Stefan Avatar asked Dec 11 '22 01:12

Stefan


1 Answers

The way to do this with AutoMapper is to use .ConstructUsing:

Mapper.CreateMap<string, Class>()
    .ConstructUsing(str => new Class { MyProp = str });

Example: https://dotnetfiddle.net/0Vlc8b

like image 82
Andrew Whitaker Avatar answered Jan 19 '23 03:01

Andrew Whitaker