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

♀尐吖头ヾ 提交于 2020-05-29 02:32:33

问题


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();

回答1:


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);




回答2:


If you want to concatenate all values in your list of string you need to use string.Join. In mapper you need to use ForMember method.

From UserEditViewModel to User:

Mapper.CreateMap<User, UserEditViewModel>().ForMember(user => user.Role, opt => opt.MapFrom(userEdit => string.Join(", ", userEdit.Roles)));

From User to UserEditViewModel:

Mapper.CreateMap<UserEditViewModel, User>().ForMember(userEdit => userEdit.Roles, opt => opt.MapFrom(user => user.Role.Split(",").ToList()));



回答3:


I think you should be able to use the AutoMapper AfterMap, something like this:

.AfterMap((src,dest) => dest.Roles.Add(src.Role))

Credit to the answer here: Map a property to a collection item



来源:https://stackoverflow.com/questions/35008760/mapping-string-to-liststring-and-vice-versa-using-automapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!