private UserDetailEditViewModel ConvertToUserDetailEditViewModel(ApplicationUser user) { UserDetailEditViewModel result = null; if (user.Singer != null) { result = new UserDetailEditViewModel { UserId = user.Id, Email = user.Email, PhoneNumber = user.PhoneNumber, CanLogin = user.CanLogin, LastLogin = user.LastLogin, CreatedOn = user.CreatedOn, GdprApproved = user.GdprApproved, SingerId = user.Singer.Id, FirstName = user.Singer.FirstName, Surname = user.Singer.Surname, }; } else if (user.Choirmaster != null) { result = new UserDetailEditViewModel { UserId = user.Id, Email = user.Email, PhoneNumber = user.PhoneNumber, CanLogin = user.CanLogin, LastLogin = user.LastLogin, CreatedOn = user.CreatedOn, GdprApproved = user.GdprApproved, ChoirmasterId = user.Choirmaster.Id, FirstName = user.Choirmaster.FirstName, Surname = user.Choirmaster.Surname, }; } else { result = new UserDetailEditViewModel { UserId = user.Id, Email = user.Email, PhoneNumber = user.PhoneNumber, CanLogin = user.CanLogin, LastLogin = user.LastLogin, CreatedOn = user.CreatedOn, GdprApproved = user.GdprApproved, }; } return(result); }
private ApplicationUser MergeUserWithEditModel(ApplicationUser user, UserDetailEditViewModel model) { user.CanLogin = model.CanLogin; if (user.Singer != null) { user.Singer.FirstName = model.FirstName; user.Singer.Surname = model.Surname; } else if (user.Choirmaster != null) { user.Choirmaster.FirstName = model.FirstName; user.Choirmaster.Surname = model.Surname; } return(user); }
public async Task <IActionResult> Edit(string id, [Bind] UserDetailEditViewModel model) { if (ModelState.IsValid) { var user = _userMapper.Find(id); // loads Singer and Choirmaster property too var updatedUser = MergeUserWithEditModel(user, model); var updateUserResult = await _userManager.UpdateAsync(updatedUser); if (!updateUserResult.Succeeded) { AddErrors(updateUserResult); return(View(model)); } var currentRoles = await _userManager.GetRolesAsync(updatedUser); var newRoles = model.SelectedRoles; IEnumerable <string> rolesToBeRemoved = currentRoles.Except(newRoles); IEnumerable <string> rolesToBeAdded = newRoles.Except(currentRoles); var removeRolesResult = await _userManager.RemoveFromRolesAsync(updatedUser, rolesToBeRemoved); var addRolesResult = await _userManager.AddToRolesAsync(updatedUser, rolesToBeAdded); if (!(removeRolesResult.Succeeded && addRolesResult.Succeeded)) { AddErrors(removeRolesResult); AddErrors(addRolesResult); return(View(model)); } return(RedirectToAction(nameof(Admin))); } ; return(View(model)); }