Files
chapter-organizer/WebApp/Services/EventDefinitionService.cs
T
poprhythm 8af86e22d9 Refactor collection initializers to use C# 12 collection expressions
This commit updates various files across the Core and WebApp projects to replace traditional collection initializers with C# 12 collection expressions. Changes include modifications to EventAssignment.cs, TeamScheduler_DecisionTree.cs, CareerField.cs, EventDefinition.cs, and several components in the WebApp. These updates enhance code readability and maintainability by adhering to modern C# syntax standards.
2026-01-11 10:35:58 -05:00

84 lines
2.8 KiB
C#

using Core.Entities;
using Core.Utility;
using Data;
using Microsoft.EntityFrameworkCore;
namespace WebApp.Services;
/// <summary>
/// Service for handling EventDefinition-related operations
/// </summary>
public class EventDefinitionService
{
private readonly AppDbContext _context;
public EventDefinitionService(AppDbContext context)
{
_context = context;
}
/// <summary>
/// Processes and normalizes related careers for an EventDefinition.
/// Matches existing careers by normalized name (case-insensitive) or creates new ones.
/// </summary>
/// <param name="eventDefinition">The EventDefinition to process careers for</param>
public async Task ProcessRelatedCareersAsync(EventDefinition eventDefinition)
{
if (string.IsNullOrWhiteSpace(eventDefinition.RelatedCareersText))
{
eventDefinition.RelatedCareers.Clear();
return;
}
var normalizedNames = CareerNormalizer.NormalizeCareerNames(eventDefinition.RelatedCareersText).ToList();
if (!normalizedNames.Any())
{
eventDefinition.RelatedCareers.Clear();
return;
}
// Get all existing careers from database (case-insensitive lookup)
var existingCareers = await _context.Careers
.AsNoTracking()
.Where(c => !string.IsNullOrWhiteSpace(c.Name))
.ToListAsync();
// Build lookup dictionary, handling potential duplicates by taking the first occurrence
var careerLookup = new Dictionary<string, Career>(StringComparer.OrdinalIgnoreCase);
foreach (var career in existingCareers)
{
var normalizedKey = CareerNormalizer.GetNormalizedKey(career.Name);
if (!careerLookup.ContainsKey(normalizedKey))
{
careerLookup[normalizedKey] = career;
}
}
var careersToAdd = new List<Career>();
foreach (var normalizedName in normalizedNames)
{
var normalizedKey = CareerNormalizer.GetNormalizedKey(normalizedName);
if (careerLookup.TryGetValue(normalizedKey, out var existingCareer))
{
// Use existing career (preserve original capitalization)
careersToAdd.Add(existingCareer);
}
else
{
// Create new career with the normalized name (preserving capitalization from input)
var newCareer = new Career { Name = normalizedName };
_context.Careers.Add(newCareer);
careersToAdd.Add(newCareer);
careerLookup[normalizedKey] = newCareer;
}
}
// Replace the collection
eventDefinition.RelatedCareers = careersToAdd;
}
}