This repository was archived by the owner on May 26, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathDeleteQuestionOptionHandler.cs
More file actions
94 lines (74 loc) · 2.93 KB
/
Copy pathDeleteQuestionOptionHandler.cs
File metadata and controls
94 lines (74 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using VoteMonitor.Api.Form.Commands;
using VoteMonitor.Entities;
namespace VoteMonitor.Api.Form.Handlers
{
public class DeleteQuestionOptionHandler : IRequestHandler<DeleteQuestionOptionCommand, bool>
{
private readonly VoteMonitorContext _context;
public DeleteQuestionOptionHandler(VoteMonitorContext context)
{
_context = context;
}
public async Task<bool> Handle(DeleteQuestionOptionCommand request, CancellationToken cancellationToken)
{
using (var transaction = await _context.Database.BeginTransactionAsync(cancellationToken))
{
var optionToBeRemoved = _context.Options.FirstOrDefault(o => o.Id == request.OptionId);
if (optionToBeRemoved == null)
{
return false;
}
if (await OptionToBeDeleted(request.OptionId))
{
if (await OptionHasAnswers(request.OptionId))
{
return false;
}
await DeleteQuestionsToOption(request.OptionId);
DeleteOption(optionToBeRemoved);
}
else
{
RemoveOptionFromQuestion(request.SectionId, request.QuestionId, request.OptionId);
}
await _context.SaveChangesAsync();
await transaction.CommitAsync(cancellationToken);
return true;
}
}
private void RemoveOptionFromQuestion(int sectionId, int questionId, int optionId)
{
var questionOptionLinkToBeRemoved = _context.Questions.Where(q => q.IdSection == sectionId && q.Id == questionId)
.SelectMany(q => q.OptionsToQuestions)
.Where(otq => otq.IdOption == optionId).FirstOrDefault();
_context.Remove(questionOptionLinkToBeRemoved);
}
private async Task<bool> OptionToBeDeleted(int optiondId)
{
var atMostOnOneQuestion = await _context.OptionsToQuestions
.Where(o => o.IdOption == optiondId).CountAsync() <= 1;
return atMostOnOneQuestion;
}
private async Task<bool> OptionHasAnswers(int optionId)
{
return await _context
.Answers.Where(a => a.OptionAnswered.IdOption == optionId).AnyAsync();
}
private async Task DeleteQuestionsToOption(int optionId)
{
var questionsToOptions = await _context.OptionsToQuestions.Where(otq => otq.IdOption == optionId).ToListAsync();
_context.RemoveRange(questionsToOptions);
}
private void DeleteOption(Option option)
{
_context.Remove(option);
}
}
}