Linq2Sql DataContext 和 TransactionScope,嵌套方式错误?
在我们当前的项目中,我们有时会像这样嵌套 DataContext 和 TransactionScope 的创建:
using(var dc = OurDataContext.CreateInstance())
{
DoSomething(dc);
...
}
void DoSomething(OurDataContext dc)
{
using(var scope = new TransactionScope())
{
// DoSomethingElse() might call dc.SubmitChanges() which is why
// we inserted the TransactionScope here
DoSomethingElse(dc);
dc.SubmitChanges();
scope.Complete();
}
}
这真的像我们期望的那样工作吗?
(尽管截止日期很紧,但发现这样的代码还是很尴尬的。)
In our current project it has occurred that we sometimes nest the creation of a DataContext and TransactionScope like this:
using(var dc = OurDataContext.CreateInstance())
{
DoSomething(dc);
...
}
void DoSomething(OurDataContext dc)
{
using(var scope = new TransactionScope())
{
// DoSomethingElse() might call dc.SubmitChanges() which is why
// we inserted the TransactionScope here
DoSomethingElse(dc);
dc.SubmitChanges();
scope.Complete();
}
}
Does this really work as we expect it to?
(Even though deadlines were tight, it's quite embarrassing to discover code like this.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您有更多时间,这可能不完全是您的做法,它应该按您的预期工作。您拥有单个数据上下文的事务范围,并且您的所有工作都在该事务范围内完成。它应该按照您期望的方式提交或回滚。
您可能意识到传递数据上下文对象可能不是共享上下文对象的最有效方法。一种可能的替代方法是创建一个上下文对象,然后使用 ThreadStaticObject 在方法之间共享它。我们经常这样做。
This may not be exactly the way you'd do it if you had more time, it should work as you expect. You have a transaction scope for a single data context and all your work is being done within the scope of that transaction. It should commit or rollback the way you expect it to.
You probably realize that passing around a data context object probably isn't the most efficient way to share a context object. One possible alternative is to create a context object and then use ThreadStaticObject to share it among methods. We do this quite often.