c# - 忽略一项的嵌套列表的自动映射器

标签 c# automapper

我有以下模型,用户模型有角色列表。

public class User
{
    public string Username { get; set; }
    public List<Role> Roles { get; set; }
}

public class Role
{
    public Guid RoleID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}


public class UserSourceModel
{
    public string Username { get; set; }
    public List<RoleSourceModel> Roles { get; set; }
}

public class RoleSourceModel
{
    public string Name { get; set; }
    public string Value { get; set; }
}

映射器:

 Mapper.CreateMap<UserSourceModel, User>();
            Mapper.CreateMap<RoleSourceModel, Role>()
                .ForMember(dest => dest.RoleID, opt => opt.Ignore());

我不希望 RoleID 从源映射,所以我已经提到这个忽略并保留来自目标的值。

虚拟数据:

            //// data from UI
            UserSourceModel sourceData = new UserSourceModel
            {
                Username = "NewUser",
                Roles = new List<RoleSourceModel> { new RoleSourceModel { Name = "Admin", Value = "Admin" } }
            };

            //// data in database
            User destinationData = new User
            {
                Username = "UserInDB",
                Roles = new List<Role> { new Role { RoleID = Guid.NewGuid(), Name = "Staff", Value = "Staff" } }
            };

尝试映射:

var userOutPut = Mapper.Map<UserSourceModel, User>(sourceData, destinationData);

enter image description here

我希望 RoleID 应该是用户模型中已有的值 (Guid.NewGuid()),但我得到的是空 Guid (00000000-0000-0000-0000- 000000000000).

最佳答案

对我来说,使用 List<> 和 UseDestinationValue()

Mapper.CreateMap<UserSourceModel, User>();
Mapper.CreateMap<List<RoleSourceModel>, List<Role>>();
Mapper.CreateMap<RoleSourceModel, Role>()
    .ForMember(dest => dest.RoleID, opt => opt.UseDestinationValue());

关于c# - 忽略一项的嵌套列表的自动映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19651279/

相关文章:

c# - 构建一个 "scriptable"应用程序

c# - LIKE 命令 Mysql

c# - 可以使用 AutoMapper 将一个对象映射到对象列表吗?

c# - .net 中的对象复制方法 : Auto Mapper, Emit Mapper、隐式操作、属性复制

c# - 在通用 Windows 应用程序中使用 MVVM Light 进行验证

c# - EF Core 无法将值 null 插入到具有默认值的列中

asp.net-mvc - Automapper 从嵌套类映射到单个(展平)

c# - 使用 Automapper 映射自引用关系

c# - 每次项目运行时,带有主菜单的窗体都会缩小

c# - 自动映射器 3 访问目标 getter