using DB.HubXDB; using HubX.Library.Config; using Microsoft.EntityFrameworkCore; using SystemX.Core.Config.Model; using SystemX.Core.DB; using SystemX.Core.Services; namespace HubX.Server.Services { public class EFCoreService { private readonly Dictionary DicDbContext = new Dictionary(); private readonly ConfigService _configService; public EFCoreService(ConfigService configService) { _configService = configService; InitializeDB(); } #region Initialize DBContext private void InitializeDB() { var dbList = _configService.GetConfig()?.DataBase; if (dbList is not null) { foreach (var db in dbList) { if (typeof(HubXContext).Name == db.DBContext) { CreateDBContext(db); } } } } private void CreateDBContext(DataBase? dbConfig) where TDBContext : DbContext, new() { var connectionString = dbConfig?.ConvertToConnectionString(); var dbContext = new TDBContext(); dbContext.Database.SetConnectionString($"{connectionString}"); if (dbContext is not null) DicDbContext.Add($"{dbConfig?.DBContext}_{dbConfig?.DBID}", dbContext); } #endregion public TDBContext? GetDBContext(int dbID = 1) where TDBContext : DbContext { TDBContext? dBContext = default; var dbContextType = typeof(TDBContext); if (DicDbContext.TryGetValue($"{dbContextType.Name}_{dbID}", out var context) == true) { dBContext = context as TDBContext; } return dBContext; } }//class end }