0

我正在尝试在 Web 应用程序中围绕 EF4 的 ObjectContext 实现工作统一。UoW 是一个 HttpModule。我需要的是获取连接的当前事务。当一个 http 请求第一次出现时,我使用 context.Connection.BeginTransaction() 在 objectContext 上启动事务。在请求端,我需要检索连接的当前事务,但在 Connection 对象上没有执行此操作的属性。我制作了以下代码来实现它,但它不起作用。

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;
             }

我不明白为什么 command.Transaction总是 null。如果我尝试执行 GetSession().Connection.BeginTransaction() 我会得到异常事务已经存在并且无法并行启动多个事务。

GetSession() 仅从 HttpContext.Current.Items 中检索当前的 EF ObjectContext。ObjectContext 存储在 beginRequest 上。

如果您给我一些指导,我将不胜感激。

谢谢。

4

1 回答 1

0

ObjectContext.Connection不是您的商店连接;这是一个实体连接。

你可能想要TransactionScope. 如果您只想在商店开始交易,那么您需要((EntityConnection)Context.Connection).StoreConnection.

于 2011-02-07T16:57:23.503 回答