public async Task <Guid> UpdateAsync(Guid id, UserForUpdationDto updationDto) { var user = await _entity.SingleOrDefaultAsync(r => r.Id == id); if (user == null) { throw new InvalidOperationException("Can not find object with this Id."); } foreach (PropertyInfo propertyInfo in updationDto.GetType().GetProperties()) { string key = propertyInfo.Name; if (key != "Id" && user.GetType().GetProperty(key) != null) { user.GetType().GetProperty(key).SetValue(user, propertyInfo.GetValue(updationDto, null)); } } user.UserName = updationDto.Email; var roles = await _userManager.GetRolesAsync(user); await _userManager.RemoveFromRolesAsync(user, roles.ToArray()); await _userManager.AddToRolesAsync(user, updationDto.RoleNames); _entity.Update(user); var updated = await _context.SaveChangesAsync(); if (updated < 1) { throw new InvalidOperationException("Database context could not update data."); } return(id); }
public async Task <Guid> UpdateAsync(Guid id, UserForUpdationDto updationDto) { var user = await _entity.SingleOrDefaultAsync(r => r.Id == id); if (user == null) { throw new InvalidOperationException("Can not find object with this Id."); } foreach (PropertyInfo propertyInfo in updationDto.GetType().GetProperties()) { string key = propertyInfo.Name; if (key != "Id" && user.GetType().GetProperty(key) != null) { user.GetType().GetProperty(key).SetValue(user, propertyInfo.GetValue(updationDto, null)); } } var roles = await _userManager.GetRolesAsync(user); await _userManager.RemoveFromRolesAsync(user, roles.ToArray()); await _userManager.AddToRolesAsync(user, updationDto.RoleNames); _entity.Update(user); var currentUserStorages = await _context.UserStorages.Where(us => us.UserId == user.Id).ToListAsync(); foreach (var userStorage in currentUserStorages) { var updatedId = updationDto.StorageIds.SingleOrDefault(s => s == userStorage.StorageId); if (updatedId == Guid.Empty) { _context.UserStorages.Remove(userStorage); } } foreach (var storageId in updationDto.StorageIds) { var currentUserStorage = currentUserStorages.SingleOrDefault(us => us.StorageId == storageId); if (currentUserStorage == null) { var userStorage = new UserStorageEntity() { StorageId = storageId, UserId = user.Id }; await _context.AddAsync(userStorage); } } var updated = await _context.SaveChangesAsync(); if (updated < 1) { throw new InvalidOperationException("Database context could not update data."); } return(id); }