首先使用实体​​框架代码进行交易 [英] Doing transactions with Entity Framework Code First

查看:70
本文介绍了首先使用实体​​框架代码进行交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处有一个答案,以解释如何使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆