using Microsoft.EntityFrameworkCore; using PCC2.AssemblyInject.Interfaces; using System.Runtime.CompilerServices; using PCC2.Data.Entity; using static Dapper.SqlMapper; namespace PCC2.Data; internal class DbAccess : IAssemblyInjectSingleton { public DbAccess(ILogger logger) { logger.LogInformation($"Init: Create DbContext Instance..."); using var db = new Pcc2DbContext(); logger.LogInformation($"Init: Call CanConnect() ..."); if (db.Database.CanConnect() == false) { logger.LogInformation($"Init: Creating Database..."); db.Database.EnsureCreated(); logger.LogInformation($"Creating Database: OK"); } else { logger.LogInformation($"Init: OK"); } } public static Pcc2DbContext GetDbContext() => new(); public static SettingOnDb GetSettings() => new(GetDbContext()); internal class SettingOnDb(Pcc2DbContext dbContext) : IDisposable, IAsyncDisposable { private readonly DbSet Settings = dbContext.Settings; public void Dispose() => dbContext.Dispose(); public async ValueTask DisposeAsync() => await dbContext.DisposeAsync(); private string? GetValue([CallerMemberName] string key = "") => Settings.Where(p => p.Key == key).Select(p => p.Value).SingleOrDefault(); private int? GetInt32Value([CallerMemberName] string key = "") => int.TryParse(GetValue(key), out var i32) ? i32 : null; private void SetValue(string? value, [CallerMemberName] string key = "") { var entity = new Setting { Key = key, Value = value }; if (Settings.Any(p => p.Key == key)) dbContext.Attach(entity).Property(nameof(entity.Value)).IsModified = true; else Settings.Add(entity); dbContext.SaveChanges(); } public string? ListenAddress { get => GetValue(); set => SetValue(value); } public int? ListenPort { get => GetInt32Value(); set => SetValue(value?.ToString()); } } }