public async Task <QuestionDTOEnvelope> Handle(Request request, CancellationToken cancellationToken) { var userId = currentUserAccessor.GetCurrentUserId(); var question = context.Questions.Where(q => q.Id == request.Question.Id) .Include(q => q.AnswerOptions).FirstOrDefault(); if (question == null) { throw new Exceptions.QuestionNotFoundException(); } var examId = question.ExamId; var exam = context.Exams.NotPublishedByIdAndUserId(examId, userId).FirstOrDefault(); if (exam == null) { throw new Exceptions.ExamNotFoundException(); } var utcNow = DateTime.UtcNow; var answers = request.Question.Answers; bool hasAnswersChanged = false; if (answers != null && answers.Count() > 0) { hasAnswersChanged = await SaveAnswers(question, utcNow, answers, cancellationToken); } question.Text = request.Question.Text ?? question.Text; question.QuestionTypeId = request.Question.QuestionTypeId; if (context.IsModified(question) || hasAnswersChanged) { question.UpdatedAt = utcNow; } await context.SaveChangesAsync(); var questionDto = mapper.Map <Domain.Question, QuestionDTO>(question); return(new QuestionDTOEnvelope(questionDto)); }
public async Task <ExamDTOEnvelope> Handle(Request request, CancellationToken cancellationToken) { var userId = currentUserAccessor.GetCurrentUserId(); var examData = request.Exam; var exam = await context.Exams.NotPublishedByIdAndUserId(request.Id, userId) .IncludeTags() .FirstOrDefaultAsync(cancellationToken); if (exam == null) { throw new Exceptions.ExamNotFoundException(); } exam.Title = examData.Title ?? exam.Title; exam.Description = examData.Description ?? exam.Description; exam.TimeInMinutes = examData.TimeInMinutes ?? exam.TimeInMinutes; exam.PassPercentage = examData.PassPercentage ?? exam.PassPercentage; exam.IsPrivate = examData.IsPrivate ?? exam.IsPrivate; var examTagsToAdd = Array.Empty <Domain.ExamTag>(); var examTagsToDelete = Array.Empty <Domain.ExamTag>(); if (request.Exam.Tags != null) { var tags = await context.SaveTagsAsync(request.Exam.Tags ?? Enumerable.Empty <string>(), cancellationToken); var examTags = exam.ExamTags; examTagsToDelete = examTags.Where(et => !tags.Any(t => t.TagId == et.TagId)).ToArray(); examTagsToAdd = tags.Where(t => !examTags.Any(et => et.TagId == t.TagId)) .Select(t => new Domain.ExamTag() { Tag = t, TagId = t.TagId, Exam = exam, ExamId = exam.Id }).ToArray(); } if (context.IsModified(exam) || examTagsToAdd.Length > 0 || examTagsToDelete.Length > 0) { exam.UpdatedAt = DateTime.UtcNow; } await context.ExamTags.AddRangeAsync(examTagsToAdd, cancellationToken); context.ExamTags.RemoveRange(examTagsToDelete); await context.SaveChangesAsync(cancellationToken); var examDto = mapper.Map <Domain.Exam, ExamDTO>(exam); return(new ExamDTOEnvelope(examDto)); }