You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
3.1 KiB
82 lines
3.1 KiB
1 year ago
|
using System;
|
||
|
using System.Data.Entity;
|
||
|
using System.Data.SqlClient;
|
||
|
using System.Text;
|
||
|
using CK.SCP.Utils;
|
||
|
|
||
|
|
||
|
namespace ChangkeTec.SDMS.Model
|
||
|
{
|
||
|
public static class DbContextFactory
|
||
|
{
|
||
|
static DbContextFactory()
|
||
|
{
|
||
|
Database.SetInitializer<DataCenterContext>(null);
|
||
|
Database.SetInitializer<ExchangeCenterContext>(null);
|
||
|
}
|
||
|
|
||
|
|
||
|
public static DataCenterContext CreateDataCenterInstance()
|
||
|
{
|
||
|
var dbSetting = GlobalConfig.DataCenterDB;
|
||
|
try
|
||
|
{
|
||
|
DataCenterContext db;
|
||
|
var strConn = GetEfConnectionString(dbSetting);
|
||
|
db = new DataCenterContext(strConn);
|
||
|
|
||
|
return db;
|
||
|
}
|
||
|
catch (SqlException ex)
|
||
|
{
|
||
|
throw new Exception($"系统无法连接到数据库:{dbSetting},请检查配置的服务器,数据库,用户名和密码等信息是否正确。{Environment.NewLine}{ex}");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static ExchangeCenterContext CreateExchangeCenterInstance()
|
||
|
{
|
||
|
var dbSetting = GlobalConfig.ExchangeCenterDB;
|
||
|
try
|
||
|
{
|
||
|
ExchangeCenterContext db;
|
||
|
var strConn = GetEfConnectionString(dbSetting);
|
||
|
db = new ExchangeCenterContext(strConn);
|
||
|
return db;
|
||
|
}
|
||
|
catch (SqlException ex)
|
||
|
{
|
||
|
throw new Exception($"系统无法连接到数据库:{dbSetting},请检查配置的服务器,数据库,用户名和密码等信息是否正确。{Environment.NewLine}{ex}");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private static string GetEfConnectionString(DbSetting dbSetting)
|
||
|
{
|
||
|
var sbConn = new StringBuilder();
|
||
|
|
||
|
if (string.IsNullOrEmpty(dbSetting.密码)) throw new Exception("配置文件错误,请检查");
|
||
|
switch (dbSetting.数据库类型)
|
||
|
{
|
||
|
case "SQLServer":
|
||
|
sbConn.Append($"Data source ={dbSetting.服务器地址}");
|
||
|
sbConn.Append(dbSetting.端口 == "0" ? ";" : $",{dbSetting.端口};");
|
||
|
sbConn.Append($"Initial catalog = {dbSetting.数据库名称};");
|
||
|
sbConn.Append($"User id = {dbSetting.用户名};");
|
||
|
sbConn.Append($"Password = {CK.SCP.Utils.EncryptHelper.Decrypt(dbSetting.密码)};");
|
||
|
sbConn.Append("MultipleActiveResultSets = True;");
|
||
|
sbConn.Append("persist security info = True;");
|
||
|
sbConn.Append("App = EntityFramework;");
|
||
|
break;
|
||
|
case "MySql":
|
||
|
sbConn.Append($"server ={dbSetting.服务器地址};");
|
||
|
sbConn.Append($"port ={dbSetting.端口};");
|
||
|
sbConn.Append($"database = {dbSetting.数据库名称};");
|
||
|
sbConn.Append($"user id = {dbSetting.用户名};");
|
||
|
sbConn.Append($"password = {EncryptHelper.Decrypt(dbSetting.密码)};");
|
||
|
sbConn.Append("persistsecurityinfo =True;");
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
return sbConn.ToString();
|
||
|
}
|
||
|
}
|
||
|
}
|