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);
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
).
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());
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With