简体   繁体   中英

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. Then, I have a stored procedure B that consumes this data. Hence, A and B must be called during the same session (connection). 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 . I can easily accomplish that with the TransactionScope class, but that also implies a transaction which I do not want.

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.

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

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

The same connection is used to get both resultsets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM