I am trying to map 2 models together which have some overlapping properties:
public class UserModel
{
public int UserId { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string Alias { get; set; }
}
public class ADModel
{
public string GivenName { get; set; }
public string Surname { get; set; }
}
I retrieve the UserModel from the database and want to map the ADModel on to get any updates to the record. I'm only interested in updating the UserModel properties that are on the ADModel. I have set up a mapping profile like so:
public UserProfile()
{
CreateMap<ADModel, UserModel>()
.ForMember(dest => dest.Forename, opt => opt.MapFrom(src => src.GivenName))
.ForMember(dest => dest.Surname, opt => opt.MapFrom(src => src.Surname))
.ForMember(dest => dest.Alias, opt => opt.Ignore())
.ForMember(dest => dest.UserId, opt => opt.Ignore());
}
however, it never seems to ignore the Alias or UserId property and sets them to null. I want to keep those properties as they were and overwrite forename and surname, is there keep unmapped properties the same?
I have tried here (but I don't use a constructor) and here but neither work for me. I've also been through this post and tried the UseDestinationValue()
option but that also still results in an alias of null.
Calling method, if it helps:
private void FindUpdatedUsers(IEnumerable<UserModel> existingUsers, IEnumerable<ADModel> adUsers)
{
foreach (var item in adUsers)
{
var existing = existingUsers.First(e => string.Equals(e.Surname, item.Surname, StringComparison.InvariantCultureIgnoreCase));
existing = _mapper.Map<UserModel>(item);
_userService.Update(existing);
}
}