/// <summary> /// Update scheme answers for a scheme question /// </summary> /// <remarks> /// This is the logic used to update answers for an existing scheme question. /// check old answer array against new answer array /// if an existing answer is NOT in the new array, delete the exiting answer /// if existing answer has new text, update existing answer /// add any new answers /// </remarks> /// <param name="questionToUpdate"></param> /// <param name="questionUpdates"></param> private void UpdateAnswersForQuestion(SchemeQuestion questionToUpdate, SchemeQuestionUpdateDto questionUpdates) { foreach (var oldAnswer in questionToUpdate.PossibleAnswers) { var newAnswerDto = questionUpdates.PossibleAnswers.SingleOrDefault(a => a.Id == oldAnswer.Id); if (newAnswerDto != null) { if (oldAnswer.Text != newAnswerDto.Text) { oldAnswer.Text = newAnswerDto.Text; } if (oldAnswer.Order != newAnswerDto.Order) { oldAnswer.Order = (int)newAnswerDto.Order; } } else { // This will fail if there are CodedAnswers for this SchemeAnswer. // If we want to support deleting answers, this needs to be updated. _unitOfWork.SchemeAnswers.Remove(oldAnswer); } } // Look for new answers and add them. // New answers have no Id so check for Id == null. foreach (var answer in questionUpdates.PossibleAnswers) { if (answer.Id == null) { var answerToAdd = Mapper.Map <SchemeAnswer>(answer); questionToUpdate.PossibleAnswers.Add(answerToAdd); } } }
public async Task <IActionResult> UpdateQuestion(long projectId, long questionId, [FromBody] SchemeQuestionUpdateDto questionUpdates) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _unitOfWork.Users.SingleOrDefaultAsync(u => u.Id == questionUpdates.UserId); if (!_unitOfWork.Users.CanUserEdit(user)) { return(Forbid()); } var project = await _unitOfWork.Projects.SingleOrDefaultAsync(p => p.Id == projectId); if (project.Status != (int)ProjectStatus.Active) { // project locked no update allowed return(StatusCode(403)); } if (project == null) { return(NotFound()); } var questionToUpdate = await _unitOfWork.SchemeQuestions.SingleOrDefaultAsync(sq => sq.Id == questionId); if (questionToUpdate == null) { return(NotFound()); } Mapper.Map(questionUpdates, questionToUpdate); UpdateAnswersForQuestion(questionToUpdate, questionUpdates); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } project.UpdateLastEditedDetails(user); if (await _unitOfWork.Complete() <= 0) { return(StatusCode(304)); } return(Ok(Mapper.Map <SchemeQuestionReturnDto>(questionToUpdate))); }