Connection.BeginTransaction和实体框架4? [英] Connection.BeginTransaction and Entity Framework 4?

查看:97
本文介绍了Connection.BeginTransaction和实体框架4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将EF4代码优先的事务与工作单元实现一起使用。我们不能从上下文中使用Connection.BeginTransaction吗?它仅适用于SQL事务吗?因为当我调用它时,我得到错误:非法操作。连接已关闭。

I am trying to use transactions with EF4 Code-first with an unit of work implementation. Is there a reason we cannot use Connection.BeginTransaction from the context ? It is only intended to be used in SQL transactions only ? Because when im calling it i get the error : Illegal operation. Connection is closed.

谢谢。

推荐答案

部分答案DbContext.SaveChanges()会自动进行事务处理,因此在许多情况下,您无需滚动自己的事务。您的情况是什么,为什么您认为需要手动执行事务?

Part of the answer will be that DbContext.SaveChanges() is automatically transactional, so in many cases, you will not need to roll your own transactions. What is your scenario, and why do you think that you need to manually do transactions?

如果您决定需要它们,请将SaveChanges包装在事务中:

If you decide you need them, wrap SaveChanges in a transaction:

    using (TransactionScope transaction = new TransactionScope())
    {
        context.SaveChanges();
    }

如果运行Profiler,您会注意到该交易将在您回滚后回滚离开using {}块。要提交您的交易,请调用transaction.Complete();。在SaveChanges()之后。

If you run Profiler, you will note that the transaction is rolled back once you leave the using{} block. To commit your transaction, call transaction.Complete(); after SaveChanges().

这篇关于Connection.BeginTransaction和实体框架4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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