Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper for a nested list with one item ignored

Tags:

c#

automapper

I have below models, User model have list of Roles.

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:

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

I don't want RoleID to be mapped from source, so I have mentioned this ignore and keep the value from destination.

Dummy data:

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

Tried mapping:

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

enter image description here

I expected RoleID should be the value which was already in User model (Guid.NewGuid()), but I'm getting empty Guid (00000000-0000-0000-0000-000000000000).

like image 934
HashCoder Avatar asked Oct 29 '13 06:10

HashCoder


2 Answers

For me worked with List<> and UseDestinationValue()

Mapper.CreateMap<UserSourceModel, User>();
Mapper.CreateMap<List<RoleSourceModel>, List<Role>>();
Mapper.CreateMap<RoleSourceModel, Role>()
    .ForMember(dest => dest.RoleID, opt => opt.UseDestinationValue());
like image 156
Vladimir Avatar answered Sep 25 '22 14:09

Vladimir


You need to add one more map I think.

        Mapper.CreateMap<UserSourceModel, User>();         
        Mapper.CreateMap<List<RoleSourceModel>,List<Role>>();
     Mapper.CreateMap<RoleSourceModel, Role>()
         .ForMember(dest => dest.RoleID, o => o.Ignore());
like image 37
Gireesh R S Avatar answered Sep 24 '22 14:09

Gireesh R S