[英]How can I use SqlBulkCopy from Entity Framework database connection in unknown state
I have a static helper method for bulk inserting Entity Framework objects. 我有一个用于大量插入Entity Framework对象的静态助手方法。 It works and my unit tests pass but it looks wrong and I can't help but think there must be a better way to do it. 它可以正常工作,并且我的单元测试通过了,但是看起来不对,我忍不住认为必须有更好的方法来做到这一点。
public static void BulkInsert<T>(Entities db, IList<T> list)
{
SqlTransaction transaction = db.Database.CurrentTransaction != null ? db.Database.CurrentTransaction.UnderlyingTransaction as SqlTransaction : null;
if (db.Database.Connection.State != ConnectionState.Open)
{
db.Database.Connection.Open();
}
using (var bulkCopy = new SqlBulkCopy((db.Database.Connection) as SqlConnection, SqlBulkCopyOptions.Default, transaction))
{
//fill a datatable and write to server, this bit works
}
}
It could be called inside a DbContextTransaction
and/or the DbContext.Database
might have done something already so the connection might be open. 可以在DbContextTransaction
和/或DbContext.Database
内部调用它。 DbContext.Database
可能已经完成了某些操作,因此连接可能已打开。 If you don't explicitly open the connection before creating the bulk copy you get an error: 如果在创建批量副本之前未显式打开连接,则会收到错误消息:
System.InvalidOperationException: WriteToServer requires an open and available Connection System.InvalidOperationException:WriteToServer需要打开且可用的连接
which is odd, I'd have thought that sqlBulkCopy
would have opened the connection if it had to. 奇怪的是,我曾经以为sqlBulkCopy
必须打开连接。
So my question is am I going about this the right way? 所以我的问题是我是否要正确解决这个问题?
I have used your approach successfully myself. 我本人已经成功使用了您的方法。
My feeling is that you should close it again if you opened it. 我的感觉是,如果打开它,则应再次将其关闭。
I would additionally let SqlBulkCopy
handle the transaction itself. 我还要让SqlBulkCopy
处理事务本身。 I don't think enlisting SqlBulkCopy
into any ambient transaction is a great idea unless your particular scenario absolutely demands it. 我不认为让SqlBulkCopy
任何环境事务不是一个好主意,除非您的特定情况绝对需要它。
public static void BulkInsert<T>(PandaDataContext db, IList<T> list)
{
var mustOpen = db.Database.Connection.State != ConnectionState.Open;
try
{
if (mustOpen)
db.Database.Connection.Open();
using (var bulkCopy = new SqlBulkCopy((db.Database.Connection) as SqlConnection, SqlBulkCopyOptions.Default))
{
}
}
finally
{
if (mustOpen)
db.Database.Connection.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.