Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping string to List<string> and vice versa using Automapper

Basically I have this class which represents 1:1 with my database

public class User
{
    public int UserID { get; set; }
    public string Username { get; set; }
    public string Role { get; set; }
}

and I have this viewmodel

public class UserEditViewModel
{
    public UserEditViewModel()
    {
        Roles = new List<string>();
    }

    public int UserID { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public List<string> Roles { get; set; }
}

I have no idea how to map between these 2. My current setup :

Mapper.CreateMap<UserEditViewModel, User>().ReverseMap();
like image 643
warheat1990 Avatar asked Jan 26 '16 07:01

warheat1990


People also ask

What can I use instead of AutoMapper?

Mapster is an emerging alternative to AutoMapper which was first published in 2015 and has over 7.4 million NuGet package downloads.

Can AutoMapper map collections?

AutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.


2 Answers

There is something similar to your questiong here, please can you check this out AutoMapper: Collection to Single string Property

PS: This is an example for mapping collection to single string property probably your example should look like below;

Mapper.CreateMap<User, UserEditViewModel>()
    .ForMember(dest => dest.Roles,
    m => m.MapFrom(src => src.Role.Split(',').ToList()));

And mapping the instances like below;

User myUser = new User();
myUser.Role = "r1,r2,r3,r4,r5";
myUser.UserID = 1;
myUser.Username = "MyUserName";

UserEditViewModel result = Mapper.Map<UserEditViewModel>(myUser);

enter image description here

2020 Edit: Since Expression.Call API does not support optional parameter and you should Replace src.Role.Split(',') with src.Role.Split(',', System.StringSplitOptions.None) or src.Role.Split(',', System.StringSplitOptions.RemoveEmptyEntries)

like image 143
Cihan Uygun Avatar answered Sep 22 '22 09:09

Cihan Uygun


To map a string to a collection Cihan Uygun's answer works, only to fix the error

CS0854 An expression tree may not contain a call or invocation that uses optional arguments

which is caused in later updates you should Replace src.Role.Split(',') with src.Role.Split(',', System.StringSplitOptions.None) or src.Role.Split(',', System.StringSplitOptions.RemoveEmptyEntries)

To do the reverse mapping just use src => string.Join(',', src.Roles)

Source for the error fix: https://newbedev.com/mapping-string-to-list-string-and-vice-versa-using-automapper

like image 32
Soroush Borhan Avatar answered Sep 26 '22 09:09

Soroush Borhan