An
SqlTransaction
should be used for a particular
SqlConnection
. In your case, the
SqlTransaction
belongs to another
SqlConnection
, and hence, it is throwing such Exception message.
You need to obtain the
SqlTransaction
from the
SqlConnection
obejct, by using the following piece of code:
sqlTransaction = sqlConnection.BeginTransaction();
I've provided you a sample code which you could follow:
public MyMethod()
{
SqlConnection sqlConnection = null;
SqlTransaction sqlTransaction = null;
try
{
sqlConnection = GetDataConnection();
sqlTransaction = sqlConnection.BeginTransaction();
MyMethod1(Input, sqlConnection, sqlTransaction)
MyMethod2(Input, sqlConnection, sqlTransaction)
sqlTransaction.Commit();
}
catch(Exception e)
{
if (sqlTransaction!=null) {sqlTransaction.Rollback()};
throw new Exception("Failure in method x", e) ;
}
finally
{
if(sqlConnection!=null && sqlConnection.State==ConnectionState.Open)
{
sqlConnection.Close();
}
}
}
Hope this helps