public async Task <ActionResult <QuestionResource> > CreateQuestion([FromBody] CreateQuestionResource model) { var token = Request.Headers["Authorization"].ToString(); var userToken = new JwtSecurityTokenHandler().ReadJwtToken(token); var userId = userToken.Claims.ToArray()[0].Value.ToString(); var userGuid = new Guid(userId); foreach (var quest in model.Questions) { var question = _mapper.Map <QuestionResource, QuizQuestion>(quest); var oldQuestions = await _quizQuestionService.GetAllQuestionsByEvaluationId(quest.EvaluationId); await DeleteOldQuestions(oldQuestions, model); if (quest.Id > 0) { var questionToUpdate = await _quizQuestionService.GetQuestionById(quest.Id); await _quizQuestionService.UpdateQuestion(questionToUpdate, question); var oldAnswers = await _answerService.GetAllAnswersByQuestionId(quest.Id); await DeleteOldAnswers(oldAnswers, question); foreach (var newAns in question.Answers) { if (newAns.Id > 0) { var answerToUpdate = await _answerService.GetAnswerById(newAns.Id); await _answerService.UpdateAnswer(answerToUpdate, newAns); } else { newAns.QuizQuestionId = question.Id; newAns.Status = 1; await _answerService.CreateAnswer(newAns); } } } else { var questionToAdd = _mapper.Map <QuestionResource, QuizQuestion>(quest); questionToAdd.CreatedById = userGuid; questionToAdd.EvaluationId = quest.EvaluationId; questionToAdd.Status = 1; foreach (var ans in questionToAdd.Answers) { ans.Status = 1; } var questionResult = await _quizQuestionService.CreateQuestion(questionToAdd); if (questionResult == null) { return(BadRequest()); } } } return(Ok()); }
private async Task DeleteOldQuestions(IEnumerable <QuizQuestion> oldQuestions, CreateQuestionResource model) { foreach (var oldQuest in oldQuestions) { var matches = model.Questions.Where(p => p.Id == oldQuest.Id).ToList(); if (matches.Count == 0) { await _quizQuestionService.DeleteQuestion(oldQuest); } } }