How To Handle 'No Longer Usable SqlTransaction' Error In C#

Today, I was working with one of my project and faced a problem. It was an exception: “This SqlTransaction has completed; it is no longer usable”.

This type of error comes in the project when SQL connection and transaction are handled properly in the project. You are doing some transaction in the code and let say by any reason the you suffer lost connection. Then it will throw this type of exception.

Mostly project creates a connection one time and use it across the application. If connection is being closed in between the process and you are going to roll back the transaction the error occurs. 

Error would be like the following:

This SqlTransaction has completed; it is no longer usable.

at System.Data.SqlClient.SqlTransaction.Zo eck()
at System.Data.SqlClient.SqlTransaction.Rollback()

Here's the code,

  1. SqlConnection con = new SqlConnection("server=Mukesh-pc;database=dotnetTest;integrated security=true");  
  2. SqlTransaction myTransaction;  
  3. con.Open();  
  4. myTransaction = con.BeginTransaction();  
  5. try  
  6. {  
  7.     con.Close();  
  8.     SqlCommand cmd = new SqlCommand("insert into Employee values (100,'Mukesh')");  
  9.     cmd.Connection = con;  
  10.     cmd.ExecuteNonQuery();  
  11. }  
  12. catch(Exception ex)  
  13. {  
  14.     //Not checking connection is open or not.  
  15.     myTransaction.Rollback();  
  16. }  

In above code, you can see that on the time of RollBack transaction there is no checking for connection is open or not.

To resolve this issue, you can do two things.

Firstly, you can handle the exception into the catch block and show a proper message for it. See the following code.

  1. SqlTransaction myTransaction;  
  2. con.Open();  
  3. myTransaction = con.BeginTransaction();  
  4. try  
  5. {  
  6.     con.Close();  
  7.     SqlCommand cmd = new SqlCommand("insert into Employee values (100,'Mukesh')");  
  8.     cmd.Connection = con;  
  9.     cmd.ExecuteNonQuery();  
  10. }  
  11. catch(Exception ex)  
  12. {  
  13.     try  
  14.     {  
  15.         myTransaction.Rollback();  
  16.     }  
  17.     catch(Exception ex1)  
  18.     {  
  19.         //Hanlde the exception and log the proper message for this..  
  20.         Console.WriteLine("Rollback Exception Type", ex1.StackTrace.ToString());  
  21.     }  
  22. }  
Secondly, if you are using the Web.Config file, there you can add the following lines of code.
  1. <defaultSqlTimeoutSecs value="1000" />  
  2. <longSqlTimeoutSecs value="1500" />  
And increase the timeout value to resolve this issue.
 
Thanks for reading the article. Hope you enjoyed it.

 

Up Next
    Ebook Download
    View all
    Learn
    View all