Linq2Sql DataContext 和 TransactionScope,嵌套方式错误?

发布于 2024-12-17 08:41:45 字数 533 浏览 0 评论 0原文

在我们当前的项目中,我们有时会像这样嵌套 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤千羽 2024-12-24 08:41:45

如果您有更多时间,这可能不完全是您的做法,它应该按您的预期工作。您拥有单个数据上下文的事务范围,并且您的所有工作都在该事务范围内完成。它应该按照您期望的方式提交或回滚。

您可能意识到传递数据上下文对象可能不是共享上下文对象的最有效方法。一种可能的替代方法是创建一个上下文对象,然后使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文