有没有办法将 TransactionScope 与现有连接一起使用?

发布于 2024-07-21 16:30:13 字数 132 浏览 4 评论 0原文

我有一些代码的工作方式类似于 TransactionScope 的建议使用,但具有环境连接而不是环境事务。

有没有办法将 TransactionScope 对象与现有连接一起使用,或者 .Net 框架中是否有替代方案来实现此目的?

I have some code that works like the advised use of TransactionScope, but has an ambient connection instead of an ambient transaction.

Is there a way to use a TransactionScope object with an existing connection, or is there an alternative in the .Net framework for this purpose?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

烟凡古楼 2024-07-28 16:30:14

要将连接登记到 TransactionScope 中,您需要在其连接字符串中指定 'Enlist=true' 并在该 TransactionScope 对象的范围中打开该连接。

您可以在现有连接上使用SqlConnection.BeginTransaction

更新:您可以像这样使用BeginTransaction吗:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    SqlCommand command = connection.CreateCommand();
    SqlTransaction transaction;

    // Start a local transaction.
    transaction = connection.BeginTransaction("SampleTransaction");

    // Must assign both transaction object and connection
    // to Command object for a pending local transaction
    command.Connection = connection;
    command.Transaction = transaction;

    ...
    ...

}

To enlist a connection into a TransactionScope, you need to specify 'Enlist=true' in its connection string and open the connection in the scope of that TransactionScope object.

You can use SqlConnection.BeginTransaction on an existing connection.

Update: Can you use BeginTransaction like this:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    SqlCommand command = connection.CreateCommand();
    SqlTransaction transaction;

    // Start a local transaction.
    transaction = connection.BeginTransaction("SampleTransaction");

    // Must assign both transaction object and connection
    // to Command object for a pending local transaction
    command.Connection = connection;
    command.Transaction = transaction;

    ...
    ...

}
心房敞 2024-07-28 16:30:14

经过更多研究,我的问题的答案是:

不,需要在实例化 TransactionScope 对象后打开连接。

After more research, the answer to my question turned out to be:

No, the connection needs to be opened after the TransactionScope object is instantiated.

我为君王 2024-07-28 16:30:13

事实上,有一种方法。

connection.EnlistTransaction(Transaction.Current)

它有效,如果没有必要,它不会促进交易分布式(与文档所述相反)

HTH

In fact, there is one way.

connection.EnlistTransaction(Transaction.Current)

It works and it doesnt promote transaction to distributed if not necessary (contrary to what documentation says)

HTH

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