I am trying to run ExecuteNonQuery using transaction, but I keep getting this error
OleDbException : 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.
Here is my code: What is the problem?
_dataManager = new DataManager();
bool bTrance = false;
_dataManager.BuildConnectionString("server", "MyId", "MyPwd");
_dataManager.Connect();
try
{
Console.WriteLine("Begin Trans");
var res = _dataManager.BeginTransaction();
if (res)
{
bTrance = true;
Console.WriteLine(" Trans Success");
}
Console.WriteLine("Query Executed");
return _dataManager.ExecuteQuery("call SP_MySp");
}
catch (OleDbException objDBExc)
{
Console.WriteLine("OleDbException : " + objDBExc.Message);
if (bTrance)
{
_dataManager.RollbackTransaction();
}
return false;
}
catch (Exception objExc)
{
Console.WriteLine("OleDbException : " + objExc.Message);
if (bTrance)
{
bTrance = false;
_dataManager.RollbackTransaction();
}
return false;
}
finally
{
Console.WriteLine("Done!");
if (bTrance)
{
_dataManager.CommitTransaction();
}
}
public class DataManager
{
private OleDbConnectionStringBuilder dbConnStr;
private OleDbConnection dbConn;
private OleDbTransaction dbTransaction;
private OleDbCommand dbCommand;
private bool beginTransaction;
public bool BeginTransaction()
{
try
{
if (beginTransaction == false)
{
dbTransaction = dbConn.BeginTransaction();
dbCommand.Transaction = dbTransaction;
beginTransaction = true;
}
else
dbCommand.Transaction = dbTransaction;
}
catch (Exception)
{
throw;
}
return beginTransaction;
}
public bool ExecuteQuery(string command)
{
try
{
dbCommand.ExecuteNonQuery();
}
catch (OleDbException objDbEx)
{
throw;
}
catch (Exception objEx)
{
throw;
}
dbCommand.Parameters.Clear();
dbCommand.Connection = null;
return true;
}
}
using (var tx = new TransactionScope()) { your DB code goes here }
. Callingtx.Commit()
at the end of the block unless you want to rollback. – Lashaun