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