litaoshen
litaoshen

Reputation: 1862

How to use Sql connection inside another connection?

I faced some problem about sql connection issue. The problem is I have some code like this

function1()
{
    using (sqlconnection sc = new sqlconnection())
   {
      foo();
   }
}

foo is a function like below:
foo()
{
   using (sqlconnection sc = new sqlconnection())
  {
        dosomething;
  }
}

It seems that the sqlconnection in foo() cannot work. I'm wondering if it is a good idea to pass the sqlconnection into foo like foo(sc), or is it a good idea to take foo outside function1, or is there anyway to allow the sqlconnection inside foo works.

Upvotes: 1

Views: 1722

Answers (1)

Rahul
Rahul

Reputation: 77934

No need of that, have your function foo to accepts a connection parameter and use the same connection instance in both places like below

function1()
{
    using (sqlconnection sc = new sqlconnection())
   {
      foo(sc);
   }
}

foo is a function like below:

foo(sqlconnection scc)
{
    sqlconnection sc = scc
    dosomething;
}

Upvotes: 3

Related Questions