Using the following method I am able to run a transaction against an Oracle database using ADO.NET. When I try the same code on an SQL Server database I get the error shown. What is the cause of this and how can it be fixed?
The error:
ExecuteNonQuery requires the command to have a transaction when the
connection assigned to the command is in a pending local transaction.
The Transaction property of the command has not been initialized.
The Code:
/// <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;
}
You need to assign the transaction to the command.