Abdalla Omran

Abdalla Omran

  • NA
  • 334
  • 32.4k

This SqlTransaction has completed; it is no longer usable ?

Jan 1 2020 10:06 AM
I am facing a problem with sqlbulk .
 
I have a list of PersonModel and trying to insert or save the data into SQL server but i am getting an exeption
 
private static List<PersonModel> PersonModels { get; set; }
 
AsDataTable is an Extention Method
 
its throwing an exception on transaction.Commit().... System.InvalidOperationException "This SqlTransaction has completed; it is no longer usable "
  1. using (SqlConnection connection = new SqlConnection(CS))  
  2.            {  
  3.                connection.Open();  
  4.                SqlTransaction transaction = connection.BeginTransaction();  
  5.   
  6.                using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction))  
  7.                {  
  8.                 
  9.                    bulkCopy.BatchSize = 100;  
  10.                    bulkCopy.DestinationTableName = "dbo.Person";  
  11.                    try  
  12.                    {  
  13.                        bulkCopy.WriteToServer(PersonModels.AsDataTable());  
  14.                    }  
  15.                    catch (Exception ex)  
  16.                    {  
  17.                        transaction.Rollback();  
  18.                        Console.WriteLine("Rollback Exception Type: {0}", ex.GetType());  
  19.   
  20.                        Console.WriteLine("  Message: {0}", ex.Message);  
  21.   
  22.                    }  
  23.                }  
  24.   
  25.                transaction.Commit();  
  26.            }  

Answers (1)