嵌套列表的自动映射,忽略一个项目

时间:2013-10-29 06:33:23

标签: 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)。

2 个答案:

答案 0 :(得分:7)

我使用List&lt;&gt;和UseDestinationValue()

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

答案 1 :(得分:2)

您需要再添加一张地图。

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