Implemented the deletion function

Closes #17
This commit is contained in:
tsommer committed 2022-07-09 22:21:28 +02:00
1 parent e8711de0d6
commit 271ae2a1cf
3 files changed
+63 -2

No files matched your search

@@ -82,4 +82,30 @@ public static class SectionProcessor
await db.SaveChangesAsync();
return section;
}
public static async Task RemoveSection(DataContext db, string selectedKey)
{
// Remove the section from the database:
var section2Delete = await db.Sections.FirstOrDefaultAsync(n => n.DataKey == selectedKey);
if (section2Delete is null)
throw new ArgumentException($"The section with key {selectedKey} does not exist in the database.");
// Next, remove all children of the section, and the children's children, etc.:
var children = await db.Sections.Where(n => n.Parent == section2Delete).ToListAsync();
foreach (var child in children)
await RemoveSection(db, child.DataKey);
db.Sections.Remove(section2Delete);
await db.SaveChangesAsync();
}
public static async Task<int> NumberChildren(DataContext db, string selectedKey)
{
// Read the section from the database:
var section = await db.Sections.FirstOrDefaultAsync(n => n.DataKey == selectedKey);
if (section is null)
throw new ArgumentException($"The section with key {selectedKey} does not exist in the database.");
return await db.Sections.CountAsync(n => n.Parent == section);
}
}