Implemented the section's edit function

This commit is contained in:
tsommer committed 2022-07-10 11:20:28 +02:00
1 parent aa22f7e1ef
commit 2ee393efec
6 files changed
+90 -2

No files matched your search

@@ -108,4 +108,31 @@ public static class SectionProcessor
return await db.Sections.CountAsync(n => n.Parent == section);
}
public static async Task<Section> RenameSection(DataContext db, string selectedNodeKey, string alteredName)
{
// Read the section from the database:
var section = await db.Sections.FirstOrDefaultAsync(n => n.DataKey == selectedNodeKey);
if (section is null)
throw new ArgumentException($"The section with key {selectedNodeKey} does not exist in the database.");
// Determine the new key:
var newKey = string.Join('_', alteredName.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)).ToUpperInvariant();
// Check, if this key already exists:
if (await db.Sections.AnyAsync(n => n.DataKey == newKey))
{
var rng = new Random();
while (await db.Sections.AnyAsync(n => n.DataKey == newKey))
{
// Add a random number to the end of the key:
newKey += $"_{rng.Next(1, 10_000)}";
}
}
section.Name = alteredName;
section.DataKey = newKey;
await db.SaveChangesAsync();
return section;
}
}