Cascade delete archives when deleting games

This commit is contained in:
Pat Hartl 2023-01-07 18:21:50 -06:00
parent 8b17aca569
commit 260474aee8

View file

@ -1,4 +1,5 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
@ -138,19 +139,38 @@ namespace LANCommander.Controllers
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(Guid id)
{
if (Context.Games == null)
using (Repository<Game> repo = new Repository<Game>(Context, HttpContext))
{
return Problem("Entity set 'DatabaseContext.Games' is null.");
}
var game = await Context.Games.FindAsync(id);
if (game != null)
var game = await repo.Find(id);
if (game == null)
return NotFound();
if (game.Archives != null && game.Archives.Count > 0)
{
Context.Games.Remove(game);
using (var archiveRepo = new Repository<Archive>(Context, HttpContext))
{
foreach (var archive in game.Archives.OrderByDescending(a => a.CreatedOn))
{
var archiveFile = Path.Combine("Upload", archive.ObjectKey);
if (System.IO.File.Exists(archiveFile))
System.IO.File.Delete(archiveFile);
archiveRepo.Delete(archive);
}
await Context.SaveChangesAsync();
await archiveRepo.SaveChanges();
}
}
repo.Delete(game);
await repo.SaveChanges();
return RedirectToAction(nameof(Index));
}
}
private bool GameExists(Guid id)
{