public class ManagementDBContext : DbContext
{
public static string configString = ConfigHelper.GetDatabase;
public ManagementDBContext() : base(configString)
{
Database.SetInitializer<ManagementDBContext>(null);
}
/// <summary>
/// 模型的建立
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// 判斷使用的數據庫動態控制 Schema
if (ConfigHelper.GetDBType == Enums.Database.Oracle)
{
string schema = GetConfiguration("USER ID");
modelBuilder.HasDefaultSchema(schema);
modelBuilder.Types().Configure(entity => entity.ToTable(entity.ClrType.Name, schema));
}
}
/// <summary>
/// 獲取配置鏈接串
/// </summary>
/// <param name="str">要取的字符名稱</param>
/// <returns></returns>
private static string GetConfiguration(string str)
{
if (string.IsNullOrEmpty(str)) str = str.ToUpper();
string con = ConfigHelper.GetConStrings(configString);
string[] strSplit = con.Split(';');
Dictionary<string, string> attribList = new Dictionary<string, string>();
for (int i = 0; i != strSplit.Length; i++)
{
string[] attribValue = strSplit[i].Split('=');
attribList.Add(attribValue[0], attribValue[1]);
}
return attribList[str];
}
/// <summary>
/// 導入Excel
/// </summary>
public DbSet<ImportExcel> importExcel { get; set; }
}
webconfig 內容
<connectionStrings>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=Teest;Password=Test123;Data Source=localhost:1521/orcl" />
<!--<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=databaseLog;Persist Security Info=True;MultipleActiveResultSets=True;Pooling=true;Max Pool Size=512;Min Pool Size=5;Connection Timeout=120" providerName="System.Data.SqlClient" />-->
<add name="DefaultConnection" connectionString="server=.;database=ManageDB;user id=sa;pwd=sa" providerName="System.Data.SqlClient" />
</connectionStrings>
WebConfig 裏配置
<!-- 指定鏈接數據庫 SqlServer/Oracle|0/1-->
<add key="Database" value="0" />
/// <summary>
/// 讀取配置工具類
/// </summary>
public class ConfigHelper
{
private static string temp = string.Empty;
private static string database = ConfigurationManager.AppSettings["Database"].ToString().Trim();
private static string upload = ConfigurationManager.AppSettings[StringHelper.UPLOAD.ToLower()].ToString().Trim();
private static string project = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/").ToString();
/// <summary>
/// 獲取連接的數據庫
/// </summary>
public static string GetDatabase
{
get
{
if (!string.IsNullOrEmpty(database))
return GetConnectionDefaultName(database);
else return GetConnectionStrings(StringHelper.WEBCONFIG);
}
}
/// <summary>
/// 讀取xml節點名稱,返回數據庫鏈接名稱
/// </summary>
/// <param name="xmlNodeName"></param>
/// <returns></returns>
private static string GetConnectionStrings(string fileName)
{
string[] array = null;
XmlDocument doc = new XmlDocument();
temp = project + fileName;
if (!FileHelper.FileExists(temp)) return temp;
doc.Load(temp);
XmlNodeList nodeList = doc.DocumentElement.ChildNodes;
if (nodeList.Count > 0)
foreach (XmlNode node in nodeList)
{
if (node.LocalName.ToLower() != StringHelper.CONNECTIONSTRINGS.ToLower())
continue;
array = node.InnerXml.Split('>');
array = array[0].Replace("\"", "").Split(' ');
foreach (var arr in array)
{
if (arr.ToLower().Contains(StringHelper.NAME.ToLower()))
{
array = arr.Split('=');
break;
}
}
}
return temp = array == null ? null : array[1];
}
/// <summary>
/// 動態獲取Web.config 中的連接數據庫名稱
/// </summary>
/// <param name="sqlName"></param>
/// <returns></returns>
public static string GetConnectionDefaultName(string sqlName)
{
string[] array = null;
XmlDocument doc = new XmlDocument();
temp = project + StringHelper.WEBCONFIG;
if (!FileHelper.FileExists(temp)) return temp;
doc.Load(temp);
temp = GetDataBaseName(sqlName);
XmlNodeList nodeList = doc.DocumentElement.ChildNodes;
if (nodeList.Count > 0)
{
foreach (XmlNode node in nodeList)
{
if (node.LocalName.ToLower() == StringHelper.CONNECTIONSTRINGS.ToLower())
{
array = node.InnerXml.Split('>');
break;
}
}
}
if (array.Length > 0)
{
for (int i = 0; i < array.Length - 1; i++)
{
if (array[i].ToLower().Contains(temp))
{
temp = array[i];
break;
}
}
}
array = temp.Replace("\"", "").Split(' ');
foreach (var arr in array)
{
if (arr.ToLower().Contains(StringHelper.NAME.ToLower()))
{
array = arr.Split('=');
break;
}
}
return temp = array == null ? null : array[1];
}
/// <summary>
/// 獲取上傳文件物理路徑
/// </summary>
public static string GetPhysicalPath
{
get
{
if (!string.IsNullOrEmpty(upload))
return project + upload;
else
return project + StringHelper.UPLOAD.ToLower();
}
}
/// <summary>
/// 獲取服務器文件路徑
/// </summary>
public static string GetServicePath
{
get
{
return FileHelper.IsObliqueBar(GetService) + StringHelper.UPLOAD.ToLower();
}
}
/// <summary>
/// 獲取當前項目地址以及端口號
/// </summary>
public static string GetService
{
get
{
return StringHelper.HTTP.ToLower() + "://" + StringHelper.SERVER_NAME + ":" + StringHelper.SERVER_PORT;
}
}
/// <summary>
/// 獲取連接數據庫字符串
/// </summary>
/// <param name="conName">數據庫連接名稱</param>
/// <returns></returns>
public static string GetConStrings(string conn)
{
if (!string.IsNullOrEmpty(conn))
return ConfigurationManager.ConnectionStrings[conn].ToString().ToUpper();
else
return conn;
}
/// <summary>
/// 獲取當前使用的數據庫
/// </summary>
/// <returns></returns>
public static string GetDataBaseName(string dbName)
{
try
{
temp = dbName.ToLower() == StringHelper.ORACLE.ToLower() ? StringHelper.ORACLE.ToLower() :
dbName.ToLower() == StringHelper.SQLSERVER.ToLower() ? StringHelper.SQLCLIENT.ToLower() :
Convert.ToInt32(dbName.ToLower()) == Convert.ToInt32(Database.SqlServer) ? StringHelper.SQLCLIENT.ToLower() :
Convert.ToInt32(dbName.ToLower()) == Convert.ToInt32(Database.Oracle) ? StringHelper.ORACLE.ToLower() : StringHelper.SQLCLIENT.ToLower();
}
catch (Exception)
{
temp = StringHelper.SQLCLIENT.ToLower();
}
return temp;
}
/// <summary>
/// 獲取連接數據庫類型
/// </summary>
public static Database GetDBType
{
get
{
return GetDatabaseType(database);
}
}
/// <summary>
/// 以枚舉類型返回數據庫類型
/// </summary>
/// <param name="dbType"></param>
/// <returns></returns>
public static Database GetDatabaseType(string dbType)
{
try
{
return dbType.ToLower() == StringHelper.ORACLE.ToLower() ? Database.Oracle :
dbType.ToLower() == StringHelper.SQLSERVER.ToLower() ? Database.SqlServer :
Convert.ToInt32(dbType.ToLower()) == Convert.ToInt32(Database.SqlServer) ? Database.SqlServer :
Convert.ToInt32(dbType.ToLower()) == Convert.ToInt32(Database.Oracle) ? Database.Oracle : Database.SqlServer;
}
catch (Exception)
{
return Database.SqlServer;
}
}
}
特別注意的地方就是實體類