zoukankan      html  css  js  c++  java
  • EntityFramework DBContext 类动态控制 数据库连接(支持Oracle,SQL server)

     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;
                }
            }
        }
     特别注意的地方就是实体类
     
  • 相关阅读:
    Linux/Android 系统怎么修改mac地址
    Vue.js和jQuery混合使用的一点注意事项
    wpf研究之道——datagrid控件及样式
    asp.net url重写
    如何解决一个问题
    Word 2007 封面、目录和正文页码单独设置
    .net 多线程
    我对asp.net运行机制的理解
    Firefox扩展安装
    谷歌chrome 插件(扩展)开发——谈谈安装
  • 原文地址:https://www.cnblogs.com/FGang/p/10593086.html
Copyright © 2011-2022 走看看