C # get current connection in transaction TransactionScope

I want to make a transactional series of sp calls (sql server 2005) in a .net 2.0 project surrounding some part of the business logic with

using(TransactionScope...)

Unfortunately, I inherited DAL from another project, and I do not want to make many changes there. The problem is that every method that calls a stored procedure opens a new connection.

So my question is: is there a way to get the connection used by the current transaction, i.e. from Transaction.Current ??

thank

with.

UPDATE: please tell me what is wrong with this console application (vs2005, .net 2.0, Sql server 2005)

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Transactions;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
            {
                Console.WriteLine("1");
                test();
                Console.WriteLine("2");
                test();
            }
            Console.WriteLine("END");
        }

        public static void test()
        {
            string connectionString = @"Persist Security Info=True;User ID=usr123;Password=123;Initial Catalog=db123;Data Source=myserver\myinstance;Connect Timeout=180;";

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
            }
        }
    }
}
+3
source share
3

, :

  • , TransactionScope (Sql). , , , - . MSDN System.Transactions. , , .

  • "ts.Complete()", () -Scope. , , , , .

  • , TransactionScope, , . , DTC DTC . , , .

DTC, " ", g C:\Windows\System32\com\comexp.msc. " \\ ". "". "" "MSDTC", " ...".

, :

  • " DTC"
  • " "
  • " "
  • " "
  • " (TIP)"
  • " XA"

(: , YMMV)

, " " /.

: , .

+1

, .... - Microsoft.Practices.EnterpriseLibrary.Data.TransactionScopeConnections Enterprise Library (http://entlib.codeplex.com).

+1

- , SqlConnection . - . , DAL :

...
using (var conn = new SqlConnection("connection string"))
{
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        //Do stuff with cmd
    }
}
....

( ), , , SqlConnection . - , , , SqlConnection .

0

Source: https://habr.com/ru/post/1764910/


All Articles