Пример #1
0
        /// <summary>
        /// 执行 SQL 命令
        /// </summary>
        protected virtual T DoExecute <T>(IDbCommand cmd, Func <IDbCommand, T> func, bool wasClosed, bool interceptException = true)
        {
            T TResult = default(T);

            try
            {
                if (cmd.Transaction != null && _transaction != null && cmd.Transaction != _transaction)
                {
                    throw new XFrameworkException("DoExecute: IDbCommand.Transaction does not equals to current transaction.");
                }
                if (cmd.Connection != null && _connection != null && cmd.Connection != _connection)
                {
                    throw new XFrameworkException("DoExecute: IDbCommand.Connection does not equals to current connection.");
                }

                if (cmd.Connection == null)
                {
                    cmd.Connection = this.CreateConnection();
                }
                if (cmd.Connection.State != ConnectionState.Open)
                {
                    if (string.IsNullOrEmpty(cmd.Connection.ConnectionString))
                    {
                        cmd.Connection.ConnectionString = _connString;
                    }
                    cmd.Connection.Open();
                }

                if (interceptException)
                {
                    DbInterception.OnExecuting(cmd);
                }
                TResult = func(cmd);
                if (interceptException)
                {
                    DbInterception.OnExecuted(cmd);
                }
            }
            catch (DbException e)
            {
                // 外层不捕获异常,由内层Func去捕获
                if (interceptException)
                {
                    DbInterception.OnException(new DbCommandException(e.Message, e, cmd));
                }
                throw;
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                if (wasClosed)
                {
                    this.InternalDispose();
                }
            }

            return(TResult);
        }