using FinlyticAssets.Database; using FinlyticAssets.Entities; using Microsoft.EntityFrameworkCore; namespace FinlyticAssets.Services; /// /// Defines the business logic for managing global application settings. /// Supports retrieving and updating (upserting) the central single-row configuration record. /// public interface ISettingsDbService { /// /// Retrieves the current global settings from the database. /// /// /// A task that represents the asynchronous operation. The task result contains the current . /// If no settings exist in the database yet, a new instance initialized with default values is returned. /// public Task GetSettings(); /// /// Persists the provided settings by updating the existing record or inserting the first one if the table is empty. /// /// The new configuration values to be persisted. /// /// A task that represents the asynchronous operation. The task result contains the freshly saved /// and tracked instance. /// public Task SaveSettings(Settings settings); } /// /// Implements the utilizing Entity Framework Core. /// This service is designed for a single-row table architecture to maintain stateful global configurations. /// public class SettingsDbService : ISettingsDbService { private readonly AssetsDbContext _context; /// /// Initializes a new instance of the class with the required database context. /// /// The EF Core context used to access the assets database. public SettingsDbService(AssetsDbContext context) { _context = context; } /// public async Task GetSettings() { var settings = await _context.Settings.AsNoTracking().FirstOrDefaultAsync(); if (settings == null) { settings = new Settings { Id = Guid.NewGuid() }; await SaveSettings(settings); } return settings; } /// public async Task SaveSettings(Settings settings) { var existing = await _context.Settings.FirstOrDefaultAsync(); if (existing == null) { if (settings.Id == Guid.Empty) { settings.Id = Guid.NewGuid(); } await _context.Settings.AddAsync(settings); await _context.SaveChangesAsync(); return settings; } else { _context.Entry(existing).CurrentValues.SetValues(settings); await _context.SaveChangesAsync(); return existing; } } }