コード例 #1
0
        public DbContext(string connectionName = "Default", string databaseName = null)
        {
            DbContextData data = GetDbContextData(connectionName, databaseName);

            SqlGenerator = new SqlGenerator(data.DbProvider);
            DbConnection = data.DbProviderFactory.CreateConnection();
            if (DbConnection == null)
            {
                throw new ArgumentNullException("connectionName");
            }
            DbConnection.ConnectionString = data.ConnectionString;
            if (DbConnection.State != ConnectionState.Open)
            {
                DbConnection.Open();
            }
        }
コード例 #2
0
        private DbContextData CreateDbContextData(string connectionName = "Default", string databaseName = null)
        {
            DbContextData data = new DbContextData();

            ConnectionName = connectionName;
            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings[connectionName];

            if (setting == null)
            {
                throw new Exception(string.Format("名为:{0}的节点不存在!", connectionName));
            }

            IDecryptProvider decryptProvider    = null;
            string           strDecryptProvider = ConfigurationManager.AppSettings["Dapper.Extensions.DecryptProvider"];

            if (!string.IsNullOrWhiteSpace(strDecryptProvider))
            {
                Type encryptProviderType = Type.GetType(strDecryptProvider, true);
                decryptProvider = (IDecryptProvider)Activator.CreateInstance(encryptProviderType);
            }
            string connectionString = setting.ConnectionString;

            if (decryptProvider != null)
            {
                connectionString = decryptProvider.Decrypt(setting.ConnectionString);
            }
            if (!string.IsNullOrWhiteSpace(databaseName))
            {
                connectionString = string.Format(connectionString, databaseName);
            }
            Type              dbConnectionType  = Type.GetType(setting.ProviderName, true);
            IDbProvider       dbProvider        = (IDbProvider)Activator.CreateInstance(dbConnectionType);
            DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory(dbProvider.ProviderName);

            data.ConnectionString  = connectionString;
            data.DbProvider        = dbProvider;
            data.DbProviderFactory = dbProviderFactory;
            return(data);
        }