2023-06-11 23:46:02 +00:00
|
|
|
using Microsoft.Data.SqlClient;
|
2023-07-21 21:56:14 +00:00
|
|
|
using MySqlConnector;
|
2023-06-07 00:59:32 +00:00
|
|
|
using System.Data.Common;
|
2023-06-03 02:07:30 +00:00
|
|
|
|
|
|
|
|
namespace BotSharp.Core.Repository;
|
|
|
|
|
|
|
|
|
|
public static class DataContextHelper
|
|
|
|
|
{
|
2023-09-01 22:33:36 +00:00
|
|
|
public static T GetDbContext<T, Tdb>(BotSharpDatabaseSettings settings, IServiceProvider serviceProvider)
|
2023-06-03 02:07:30 +00:00
|
|
|
where T : Database, new()
|
2023-07-21 21:56:14 +00:00
|
|
|
where Tdb : DataContext
|
2023-06-03 02:07:30 +00:00
|
|
|
{
|
|
|
|
|
if (settings.Assemblies == null)
|
|
|
|
|
throw new Exception("Please set assemblies.");
|
|
|
|
|
|
|
|
|
|
AppDomain.CurrentDomain.SetData("Assemblies", settings.Assemblies);
|
|
|
|
|
|
|
|
|
|
var dc = new T();
|
2023-08-26 04:41:01 +00:00
|
|
|
if (typeof(T) == typeof(BotSharpDbContext))
|
2023-06-11 23:46:02 +00:00
|
|
|
{
|
2023-07-21 21:56:14 +00:00
|
|
|
if (typeof(Tdb).Name.StartsWith("DbContext4SqlServer"))
|
2023-06-11 23:46:02 +00:00
|
|
|
{
|
2023-07-21 21:56:14 +00:00
|
|
|
dc.BindDbContext<IBotSharpTable, Tdb>(new DatabaseBind
|
|
|
|
|
{
|
|
|
|
|
ServiceProvider = serviceProvider,
|
|
|
|
|
MasterConnection = new SqlConnection(settings.BotSharp.Master),
|
|
|
|
|
SlaveConnections = settings.BotSharp.Slavers.Length == 0 ?
|
|
|
|
|
new List<DbConnection> { new SqlConnection(settings.BotSharp.Master) } :
|
|
|
|
|
settings.BotSharp.Slavers.Select(x => new SqlConnection(x) as DbConnection)
|
|
|
|
|
.ToList(),
|
|
|
|
|
CreateDbIfNotExist = true
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
else if (typeof(Tdb).Name.StartsWith("DbContext4Aurora") ||
|
|
|
|
|
typeof(Tdb).Name.StartsWith("DbContext4MySql"))
|
|
|
|
|
{
|
|
|
|
|
dc.BindDbContext<IBotSharpTable, Tdb>(new DatabaseBind
|
|
|
|
|
{
|
|
|
|
|
ServiceProvider = serviceProvider,
|
|
|
|
|
MasterConnection = new MySqlConnection(settings.BotSharp.Master),
|
|
|
|
|
SlaveConnections = settings.BotSharp.Slavers
|
|
|
|
|
.Select(x => new MySqlConnection(x) as DbConnection).ToList(),
|
|
|
|
|
CreateDbIfNotExist = true
|
|
|
|
|
});
|
|
|
|
|
}
|
2023-06-11 23:46:02 +00:00
|
|
|
}
|
2023-06-03 02:07:30 +00:00
|
|
|
return dc;
|
|
|
|
|
}
|
|
|
|
|
}
|