Can I use SqlBulkCopy inside Transaction

你说的曾经没有我的故事 提交于 2019-12-25 06:53:48

问题


Is it safe to use SqlBulkCopy in a TransactionScope? I am aware of this question but it does not answer the question and its pretty old. If its not possible what is a good alternative?


回答1:


It seems that if the TransactionScope is created before the sql-connection used for the SqlBulkCopy is created and opened the transaction-handling mechanics of the TransactionScope are used. Which means that you manually need to create your own SqlConnection and open it which you later use for the SqlBulkCopy instance.

using (var ts = new TransactionScope())
using (var sqlCon = new SqlConnection(conStr))
{
  sqlCon.Open(); // ensure to open it before SqlBulkCopy can open it in another transactionscope.
  using (var bulk = new SqlBulkCopy(sqlCon))
  {
    // Do you stuff
    bulk.WriteToServer...
  }      

  ts.Complete(); // finish the transaction, ie commit
}

Note 1: Changed answer heavily after reading up a bit on TransactionScope vs SqlTransaction

Note 2: This answer is purely from reading, I have no empirical evidence of the above as of now.

Note 3: There seems to be a new answer in the question you were referring to since my first reply, he gives the same answer as I do here, so I hope he has empirical evidence :) (ie https://stackoverflow.com/a/33311494/691294)



来源:https://stackoverflow.com/questions/33302905/can-i-use-sqlbulkcopy-inside-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!