将字符串映射到List< string>反之亦然,使用Automapper [英] Mapping string to List<string> and vice versa using Automapper

查看:494
本文介绍了将字符串映射到List< string>反之亦然,使用Automapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个此类,它与我的数据库代表1:1

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

我有这个viewmodel

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

推荐答案

此处与您的问题类似,请您检查一下

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

PS:这是一个将集合映射到单个字符串属性的示例,您的示例可能看起来像下面的样子;

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

2020由于Expression.Call API不支持可选参数,因此您应将src.Role.Split(',')替换为src.Role.Split(',', System.StringSplitOptions.None)src.Role.Split(',', System.StringSplitOptions.RemoveEmptyEntries)

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

这篇关于将字符串映射到List&lt; string&gt;反之亦然,使用Automapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆