EF:如何在事务中调用SaveChanges两次? [英] EF: How do I call SaveChanges twice inside a transaction?
问题描述
使用实体框架(我的例子中的代码首先),我有一个操作需要调用SaveChanges来更新数据库中的一个对象,然后再次SaveChanges来更新另一个对象。 (我需要第一个SaveChanges来解决一个问题,EF无法确定哪个对象要先更新)。
Using Entity Framework (code first in my case), I have an operation that requires me to call SaveChanges to update one object in the DB, and then SaveChanges again to update another object. (I need the first SaveChanges to resolve an issue where EF can't figure out which object to update first).
我尝试过:
using (var transaction = new TransactionScope())
{
// Do something
db.SaveChanges();
// Do something else
db.SaveChanges();
tramsaction.Complete();
}
当我运行时,我在第二个 SaveChanges
调用,说底层提供程序在打开时失败。内部异常说,我的机器上没有启用MSDTC。
When I run that, I get an exception at the second SaveChanges
call, saying "the underlying provider failed on open". The inner exception says that MSDTC is not enabled on my machine.
现在,我已经看到其他地方描述如何启用MSDTC的帖子,但似乎我也会需要启用网络访问等。这听起来像在这里完全过分,因为没有其他数据库涉及,更不用说其他服务器。我不想做一些使我的整个应用程序不那么安全(或更慢)的东西。
Now, I've seen posts elsewhere that describe how to enable MSDTC, but it seems that I would also need to enable network access, etc. This sounds like complete overkill here, since there are no other databases involved, let alone other servers. I don't want to do something that's going to make my whole application less secure (or slower).
当然,这样做一定要有一个更轻量级的方式(理想情况下没有MSDTC)?!
Surely there must be a more lightweight way of doing this (ideally without MSDTC)?!
推荐答案
这可能是由您的事务中使用的两种不同的连接引起的。尝试手动控制您的操作连接:
It is probably caused by two different connections used in your transaction. Try to control connection for your operation manually:
var objectContext = ((IObjectContextAdapter)db).ObjectContext;
try {
object.Context.Connection.Open();
using (var transaction = new TransactionScope()) {
// Do something
db.SaveChanges();
// Do something else
db.SaveChanges();
transaction.Complete();
}
} finally {
objectContext.Connection.Close();
}
这篇关于EF:如何在事务中调用SaveChanges两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!