首先使用实体框架代码进行交易 [英] Doing transactions with Entity Framework Code First
问题描述
此处有一个答案,以解释如何使用Entity Framework
进行事务处理但是,该解决方案不能首先使用代码。我尝试过的
并且测试表明以下内容确实有效
There is an answer here to explain how to do transactions with Entity Framework However the solution does not work with code first. I have experimented and my tests indicate the following does work
using (var scope = new TransactionScope())
{
DBContext1.SaveChanges()
If (ForceFailure) return 0 // used in testing
DBContext2.SaveChanges()
scope.Complete();
}
但是我感到紧张,因为我不再将参数传递给SaveChanges或调用AcceptAllChanges
However I feel nervous because I am no longer passing parameters to SaveChanges or calling AcceptAllChanges
如何确定我是否可以信任我的解决方案?
How do I establish whether I can trust my solution?
推荐答案
SaveChanges(Boolean)
是 ObjectContext
的一部分,而不是 DbContext
。请注意,不推荐使用 ObjectContext
中的方法 SaveChanges(Boolean)
,而推荐使用 SaveChanges(SaveOptions)
。
SaveChanges(Boolean)
is part of ObjectContext
, not DbContext
. Note that the method SaveChanges(Boolean)
in ObjectContext
is deprecated in favor of SaveChanges(SaveOptions)
.
如果您仍然想使用 DbContext
,则可以超载自己的 SaveChanges
使用扩展方法来使用 IObjectContextAdapter.ObjectContext 的方法例如。
If you still want to use DbContext
, you may be able to overload its own SaveChanges
method to use IObjectContextAdapter.ObjectContext, by using an extension method for example.
这篇关于首先使用实体框架代码进行交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!