Esempio n. 1
0
        /// <summary>
        /// 创建一个连接
        /// <remarks>
        ///     the connection retrieve process is as the following procedure:
        /// <list type="bullet">
        ///     <item>if no transaction exists, this method create and return a new DbConnection instance</item>
        ///     <item>if transaction exists, this method should return a cached DbConnection instance</item>
        /// </list>
        /// <param name="isConnectionCreator">输出参数,返回连接是否创建成功</param>
        /// <param name="name">数据库连接名称</param>
        /// </remarks>
        /// </summary>
        private DbConnection CreateConnection(string name, out bool isConnectionCreator)
        {
            DbConnection connection;

            isConnectionCreator = false;

            // non-transactional operation
            GraphWithoutTransaction connections = GraphWithoutTx;

            if (Transaction.Current == null)
            {
                connection = GetConnectionWithoutTx(name);
            }
            else
            {
                connection = OnGetConnectionWithTransaction(Transaction.Current);
            }

            if ((connection != null) && (connection.State != ConnectionState.Open))
            {
                if (string.IsNullOrEmpty(connection.ConnectionString))
                {
                    connection.ConnectionString = DbConnectionManager.GetConnectionString(name);
                }

                connection.Open();

                WriteTraceInfo(connection.DataSource + "." + connection.Database
                               + "[" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss.fff") + "]", " Open Connection ");
            }

            return(connection);
        }
        /// <summary>
        /// 获取一个DbContext对象
        /// </summary>
        /// <param name="name">连接名称</param>
        /// <param name="autoClose">是否自动关闭</param>
        /// <returns>DbContext对象</returns>
        public static DbContext GetContext(string name, bool autoClose)
        {
            //得到映射后连接名称
            name = DbConnectionMappingContext.GetMappedConnectionName(name);

            DbProviderFactory factory = DbConnectionManager.GetDbProviderFactory(name);

            DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder();

            csb.ConnectionString = DbConnectionManager.GetConnectionString(name);

            bool enlist = true;

            if (csb.ContainsKey("enlist"))
            {
                enlist = (bool)csb["enlist"];
            }

            DbContext result = null;

            if (enlist)
            {
                result = new AutoEnlistDbContext(name, autoClose);
            }
            else
            {
                result = new NotEnlistDbContext(name, autoClose);
            }

            result.autoClose = autoClose;

            return(result);
        }