我正在尝试在Web应用程序中围绕EF4的ObjectContext实现Unif Of Work。 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上。
如果你给我一些指导,我将不胜感激。
感谢。
答案 0 :(得分:0)
ObjectContext.Connection
不是您的商店连接;它是一个EntityConnection。
你可能想要TransactionScope
。如果您只想在商店上开始交易,那么您需要((EntityConnection)Context.Connection).StoreConnection
。