DbTransaction and DbConnection when working with EF4

发布于 2022-09-06 08:11:46 字数 1644 浏览 16 评论 0

I'm trying to implement a Unif Of Work around ObjectContext of EF4 in a web application. The UoW is an HttpModule. What I need is to get the current transaction for the connection. When an http request first commes I start the transaction on the objectContext with context.Connection.BeginTransaction(). On the request end I need to retrieve the current transaction for the connection but there is no property to do that on the Connection object. I made the following code to achieve it but it doesn't work.

private DbTransaction GetTransaction()
             {
                      if (_currentTransaction == null)
                      {
                               var command = GetSession().Connection.CreateCommand(); // just to get the current transaction
                               if (command.Transaction != null)
                                        _currentTransaction = command.Transaction;
                               else
                                        _currentTransaction = GetSession().Connection.BeginTransaction();
                      }

                      return _currentTransaction;
             }

I don't understand why the command.Transaction is always null. If I try to do GetSession().Connection.BeginTransaction() I get the exception that the transation already exists and can't start several transactions in parrallel.

GetSession() retrives just the current EF ObjectContext from HttpContext.Current.Items. ObjectContext is stored there on beginRequest.

If you give me some guidance I will appreciate.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

茶色山野 2022-09-13 08:11:46

ObjectContext.Connection isn't your store connection; it's an EntityConnection.

You probably want TransactionScope. If you want to start a transaction on the store only, then you want ((EntityConnection)Context.Connection).StoreConnection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文