是否有可能使用System.Transactions.TransactionScope与SqlBulkCopy的?有可能、System、Transactions、TransactionScope

2023-09-03 02:20:34 作者:2016大全精选

很简单的问题:是否有可能使用 System.Transactions.TransactionScope SqlBulkCopy的?文档交易和批量复制操作不提什么(至少为.NET 4.0)和我的测试表明,它不会自动的TransactionScope 入伍。

Very simple question: is it possible to use System.Transactions.TransactionScope together with SqlBulkCopy? The documentation Transaction and Bulk Copy Operations doesn't mention anything (at least as of .NET 4.0) and my testing indicates it does not automatically enlist with TransactionScope.

推荐答案

SqlBulkCopy的从来没有征到一个事务中。 的SqlCommand 还没有做到这一点。常见的误解。入伍是在一次执行在SQLConnection.open 被调用。在此之后,这是连接上运行的任何事都是暗中交易的一部分。事实上,它已不再是允许的传递一个明确的事务。

SqlBulkCopy never enlists into a transaction. SqlCommand also does not do that. Common misconception. The enlistment is performed at the time SqlConnection.Open is called. After that, anything that runs on that connection is part of the transaction implicitly. In fact it is no longer allowed to pass an explicit transaction.

如果你想 SqlBulkCopy的来参加一个 System.Transactions.Transaction 使用 TransactionScope的交易必须设置为你打开连接的时间。

If you want SqlBulkCopy to take part in a System.Transactions.Transaction using TransactionScope the transaction must be set at the time you open the connection.

这是很容易做到的:

using (var tran = new TransactionScope(...))
using (var conn = new SqlConnection(connStr))
{
  conn.Open(); //This enlists.

  using (var sqlBulkCopy = new SqlBulkCopy(conn)) {
    sqlBulkCopy.WriteToServer(...);
  }

  tran.Complete(); //Commit.
}

可能出现的错误:

Possible mistakes:

在该交易必须打开足够早。 请不要使用 SqlBulkCopy的的SqlTransaction 参数。通。 请不要使用 SqlBulkCopyOptions.UseInternalTransaction 。 The transaction must be opened early enough. Do not use the SqlTransaction parameter of SqlBulkCopy. Pass null. Do not use SqlBulkCopyOptions.UseInternalTransaction.

您可以使用任何你喜欢的批量大小,所有批次将成为交易的一部分。因此,配料的价值有限(尤其是事务日志不能被截断月初)。尝试没有配料都第一。

You can use any batch size you like and all batches will be part of the transaction. Therefore, batching has limited value (in particular the transaction log cannot be truncated early). Try no batching at all first.