63 lines
1.9 KiB
C#
63 lines
1.9 KiB
C#
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<string, DbContext> DicDbContext = new Dictionary<string, DbContext>();
|
|
private readonly ConfigService<WebApiConfig> _configService;
|
|
|
|
public EFCoreService(ConfigService<WebApiConfig> 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<HubXContext>(db);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private void CreateDBContext<TDBContext>(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<TDBContext>(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
|
|
}
|