Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlBulkCopy - Unexpected existing transaction

Tags:

I am using SqlBulkCopy to insert large amount of data:

try {    using (var bulkCopy = new SqlBulkCopy(connection))    {       connection.Open();        using (var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted))       {           bulkCopy.DestinationTableName = "table";            bulkCopy.ColumnMappings.Add("...", "...");                                        using (var dataReader = new ObjectDataReader<MyObject>(data))           {               bulkCopy.WriteToServer(dataReader);           }            tran.Commit();           return true;       }    } } catch (Exception ex) {     return false; } 

But I always get exception:

Unexpected existing transaction. 

Why this exception happens?

like image 299
1110 Avatar asked Oct 01 '13 13:10

1110


People also ask

Does SqlBulkCopy use transaction?

By default, a bulk copy operation is its own transaction. When you want to perform a dedicated bulk copy operation, create a new instance of SqlBulkCopy with a connection string, or use an existing SqlConnection object without an active transaction.

What is the use of SqlBulkCopy command?

The SqlBulkCopy class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.


1 Answers

"Unexpected existing transaction" ... Why this exception happens?

This happens because using the SqlBulkCopy constructor without specifying a transaction will create its own transaction internally.

Avoid this by creating your transaction and then use it to create the SqlBulkCopy. SqlBulkCopy can be created with the transaction that you want to use, like this:

connection.Open(); using (var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted)) {     using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, tran))     { 
like image 130
jltrem Avatar answered Jan 03 '23 02:01

jltrem