1

使用以下方法,我可以使用 ADO.NET 对 Oracle 数据库运行事务。当我在 SQL Server 数据库上尝试相同的代码时,我得到了显示的错误。这是什么原因,如何解决?

错误:

当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery 要求该命令具有事务。该命令的 Transaction 属性尚未初始化。

编码:

    /// <summary>
    /// A method to run transactional SQL on a database. Does not return a record set.
    /// </summary>
    /// <param name="transactions">A list of commands</param>
    /// <returns>A boolean indicator of success</returns>
    public bool ExecuteTransactionNonQuery(List<string> transactions)
    {
        if (transactions == null)
        {
            throw new ArgumentNullException("transactions");
        }

        PrepareConnection();

        DbTransaction dbTransaction = DBFactoryDatabaseConnection.BeginTransaction();

        try
        {
            foreach (var transaction in transactions)
            {

                DBFactoryDatabaseCommand.CommandText = transaction;
                DBFactoryDatabaseCommand.CommandType = CommandType.Text;
                DBFactoryDatabaseCommand.ExecuteNonQuery();
            }

            dbTransaction.Commit();
        }
        catch(Exception ex)
        {
            dbTransaction.Rollback();
            try
            {
                Close();
            }
            catch (Exception f)
            {
                throw new Exception("Error: Transaction execute failed on the database. " + ex.Message + ". Following that the application failed to close the connection. " + f.Message + ". ExecuteTransactionNonQuery().");
            }
            throw;
        }
        finally
        {
            dbTransaction.Dispose();
        }

        return true;
    }
4

1 回答 1

2

您需要将事务分配给命令

DBFactoryDatabaseCommand.Transaction = dbTransaction;
于 2012-08-15T14:33:33.763 回答