public void UpSertUserPermission(UserDto user) { var userPermissions = _repository.getUserPermissionByUser(user.Id).Result; var permissions = user.UserPermissionsDto.Select(p => p.PermissionId).ToArray(); userPermissions .ForEach(u => { if (!permissions.Contains(u.PermissionId)) { u.Status = false; u.LastUpdate = DateTime.Now; _repository.UpdateAsync(_mapper.Map <UserPermission>(u)); } else if (permissions.Contains(u.PermissionId) && !u.Status) { u.Status = true; u.LastUpdate = DateTime.Now; _repository.UpdateAsync(_mapper.Map <UserPermission>(u)); } } ); permissions .Where(p => !userPermissions .Select(up => up.PermissionId) .Contains(p)) .Select(p => p) .ToList() .ForEach(p => { _repository.Insert( _mapper.Map <UserPermission>(new UserPermissionDto { UserId = user.Id, PermissionId = p, LastUpdate = DateTime.Now, CreatedAt = DateTime.Now, Status = true }) ); }); }