简体   繁体   English

如何使用TransactionScope类在不启动事务的情况下使用相同的连接?

[英]How to use TransactionScope class to use same connection without starting a transaction?

I have a stored procedure A that creates a global temporary table (prefixed with ## ) where it inserts some temporary data. 我有一个存储过程A ,该存储过程A创建一个全局临时表 (前缀## ),并在其中插入一些临时数据。 Then, I have a stored procedure B that consumes this data. 然后,我有一个使用此数据的存储过程B Hence, A and B must be called during the same session (connection). 因此,必须在同一会话(连接)中调用AB Otherwise the temporary table will be dropped. 否则临时表将被删除。

My database framework constantly use a construct as follows: 我的数据库框架不断使用如下构造:

public T GetSomeData()
{
    using (var connection = OpenConnection())
    {
        // ...
    }
}

Now, I need to make sure that A and B are called on the same connection . 现在,我需要确保在相同的连接上调用AB I can easily accomplish that with the TransactionScope class, but that also implies a transaction which I do not want. 我可以使用TransactionScope类轻松完成此操作,但这也意味着我想要的事务。

using (var transaction = new TransactionScope())
{
    A();

    // Now B can read the temporary table created by A.
    // However, a transaction has been started which causes problems!
    B();

    // I don't want a transaction...
    // transaction.Complete();
}

My question is: How can I use this design pattern to create a "connection scope"? 我的问题是: 如何使用这种设计模式创建“连接范围”?

Use the same DataReader to read multiple resultsets. 使用相同的DataReader读取多个结果集。

using(var reader = command.ExecuteReader())
{
    while(reader.Read())
    {
        A();
    }
    reader.NextResult();

    while(reader.Read())
    {
        B();
    }
}

The same connection is used to get both resultsets. 相同的连接用于获取两个结果集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在SQLCLR中使用TransactionScope而不升级到MSDTC - How to use TransactionScope in SQLCLR without escalation to MSDTC 如何强制TransactionScope在数据库调用之间使用相同的连接? - How can I force TransactionScope to use the same connection across Database calls? 有没有办法将TransactionScope与现有连接一起使用? - Is there a way to use TransactionScope with an existing connection? 如何正确使用TransactionScope? - How to use TransactionScope properly? 如何使用TransactionScope? - How to use TransactionScope? 在没有参与事务的情况下在TransactionScope范围内打开新的数据库连接 - Open new database connection in scope of TransactionScope without enlisting in the transaction 如何在C#中使用TransactionScope? - How to use TransactionScope in C#? 如何在实体框架中使用TransactionScope - How to use TransactionScope in Entity Framework 具有成员资格和角色的 TransactionScope 在同一块中调用(仅使用一个连接的方式?) - TransactionScope with Membership and Roles calls in same block (way to use only one connection?) 在Windows Workflow Foundation中的TransactionScope中包装的多个活动中使用相同的数据库连接吗? - Use same db connection across multiple activities wrapped in a TransactionScope in Windows Workflow Foundation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM