public async Task <IActionResult> AddQuiz([FromBody] AddQuizRequest request) { if (!TryValidateModel(request, nameof(request))) { return(BadRequest("Invalid form data")); } var questions = request.Elements.Select(it => it.Question).ToHashSet(); if (questions.Count() != request.Elements.Count()) { return(BadRequest("All questions must be different")); } foreach (var addQuizRequestElement in request.Elements) { if (addQuizRequestElement.Answers.Contains(addQuizRequestElement.CorrectAnswer) == false) { return(BadRequest("Correct answer is not found in the available answers")); } } var model = new Quiz() { Id = Guid.NewGuid(), Elements = request.Elements.Select(it => new QuizElement(Guid.NewGuid(), it.Question, it.Answers, it.CorrectAnswer)) }; await _repo.AddQuiz(model, request.LessonId); return(Ok()); }
public async Task AddQuiz(Quiz quiz, Guid lessonId) { var lesson = await _context.Lessons.FirstOrDefaultAsync(it => it.Id == lessonId); if (lesson.QuizId != null) { throw new InvalidOperationException("Lesson already has a quiz"); } var q = new Models.Quiz() { Id = quiz.Id, Name = "Quiz" }; lesson.QuizId = quiz.Id; await _context.Quizzes.AddAsync(q); // lesson.Quiz.Elements = quiz.Elements.Select(it => new QuizElement(it.Id, it.Question, it.Answers.ToList(), it.CorrectAnswer)).ToList(); quiz.Elements.Select(it => new QuizElement(it.Id, quiz.Id, it.Question, it.Answers.ToList(), it.CorrectAnswer)).ToList().ForEach( it => { _context.QuizElements.Add(it); }); await _context.SaveChangesAsync(); }