DbTransaction and DbConnection when working with EF4
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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
.