我正在尝试在 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 上。
如果您给我一些指导,我将不胜感激。
谢谢。