Question

I have an action like following:

public JsonResult Update(UpdateUserViewModel updateUser)
{
    try
    {
        var existUser = _uow.Users.GetById(updateUser.UserId);

        AutoMapper.Mapper.CreateMap<UpdateUserViewModel,User>();
        var model = AutoMapper.Mapper.Map<User>(updateUser);

        _uow.Users.UpdateEntity(model);
        _uow.Save();

        return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message }, JsonRequestBehavior.AllowGet);
    }
}

UpdateUserViewModel does not have a Password property but User does and it is being filled in existUser. The resultant model includes Password property but not the value that was in existUser.

I do not what I am doing wrong. Please point me to right direction.

Was it helpful?

Solution

When you map with

var model = Mapper.Map<User>(updateUser);

Then new instance of destination User object is created and populated with data from updateUser. You should map from source object to existing object instead:

var existUser = _uow.Users.GetById(updateUser.UserId);
var model = Mapper.Map(updateUser, existUser);
// you even don't need model here
// just call Mapper.Map(updateUser, existUser) and use existUser

Thus AutoMapper will use existing instance of User and it will update it with data from UpdateUserViewModel.

NOTE: It's better to create mappings once on application startup.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top