public async Task Handle(RemoveHearingCommand command) { var hearing = await _context.VideoHearings .Include("HearingCases.Case") .Include("Participants.Person") .Include("Participants.Person.Address") .Include("Participants.Person.Organisation") .Include("Participants.Questionnaire") .Include("Participants.Questionnaire.SuitabilityAnswers") .SingleOrDefaultAsync(x => x.Id == command.HearingId); if (hearing == null) { throw new HearingNotFoundException(command.HearingId); } _context.RemoveRange(hearing.GetCases()); _context.Remove(hearing); var persons = hearing.Participants.Select(x => x.Person).ToList(); var organisations = persons.Where(p => p.Organisation != null).Select(x => x.Organisation).ToList(); var addresses = persons.Where(p => p.Address != null).Select(x => x.Address).ToList(); _context.RemoveRange(organisations); _context.RemoveRange(addresses); _context.RemoveRange(persons); await _context.SaveChangesAsync(); }
public async Task Handle(RemoveHearingCommand command) { var hearingsIncCloned = await _context.VideoHearings .Include(x => x.HearingCases).ThenInclude(x => x.Case) .Include(x => x.Participants).ThenInclude(x => x.Person).ThenInclude(x => x.Organisation) .Include(x => x.Participants).ThenInclude(x => x.LinkedParticipants).ThenInclude(x => x.Participant) .Include(x => x.Participants).ThenInclude(x => x.Questionnaire).ThenInclude(x => x.SuitabilityAnswers) .Include(x => x.Endpoints).ThenInclude(x => x.DefenceAdvocate) .Where(x => x.Id == command.HearingId || x.SourceId == command.HearingId).ToListAsync(); if (hearingsIncCloned.IsNullOrEmpty()) { throw new HearingNotFoundException(command.HearingId); } _context.RemoveRange(hearingsIncCloned.SelectMany(h => h.GetEndpoints())); _context.RemoveRange(hearingsIncCloned.SelectMany(h => h.GetCases())); _context.RemoveRange(hearingsIncCloned.SelectMany(h => h.Participants.SelectMany(p => p.LinkedParticipants))); var persons = GetPersonsToRemove(hearingsIncCloned); var organisations = persons.Where(p => p.Organisation != null).Select(x => x.Organisation).ToList(); _context.RemoveRange(organisations); _context.RemoveRange(persons); _context.RemoveRange(hearingsIncCloned); await _context.SaveChangesAsync(); }