26

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?

Colm Prunty
  • 1,595
  • 1
  • 11
  • 29
1110
  • 7,829
  • 55
  • 176
  • 334

2 Answers2

52

"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))
    {
jltrem
  • 12,124
  • 4
  • 40
  • 50
7

You need to use the constructor that takes in the transaction so SqlBulkCopy will be aware of the transaction

connection.Open();

using (var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted))
{
   using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, tran))
   {
       bulkCopy.DestinationTableName = "table";

       bulkCopy.ColumnMappings.Add("...", "...");                            

       using (var dataReader = new ObjectDataReader<MyObject>(data))
       {
          bulkCopy.WriteToServer(dataReader);
       }

       tran.Commit();
       return true;

   }
}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • 2
    is there a constructor that just takes connection and transaction? I think you are missing BulkCopyOptions – jltrem Oct 01 '13 at 13:25