Click here to Skip to main content
16,005,437 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
public static bool ExecuteQry(string qry, SqlConnection cnn, SqlTransaction SqlT)
		{
			bool Result=true;
			try
			{
                if (cnn.State != ConnectionState.Open)
                {
                    cnn.Open();
                }
                SqlCommand cmd = new SqlCommand(qry, cnn, SqlT);
				cmd.ExecuteNonQuery();
                cmd.Dispose();
                cnn.Close();
			}
			catch(Exception e)
			{
				
				Result=false;
			}
			return(Result);
		}



When execute this code the following exception is occur
"The transaction is either not associated with current connection or has been completed"
How can it solve

Thanks in advance
Posted
Updated 22-Dec-10 22:14pm
v2

1 solution

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
        {
            //Get Connection object
            sqlConnection = GetDataConnection();
            //Obtain SqlTransaction object from Connection object
            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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900