views:

98

answers:

4

in a using block for a connection to the entities,

How am I to reuse the connection when calling another method?

so I have:

using (SampleEntities entities = new SampleEntities()) {
    entities.Connection.Open();
    SomeMethod();

    ...
}


void SomeMethod() {
   using (SampleEntities entities = new SampleEntities())
   {
      // I want to be able to use the existing connection before the method call, any ideas?
   }

}
+3  A: 

why not have

 void SomeMethod(SampleEnities context)

and pass it in; let the first "using" sort out disposal.

Kindness,

Dan

Daniel Elliott
+1  A: 

Provided that you are using the same connection string, the connection pool is handled for you.

Even though you are using dispose, it doesn't close the connection. It returns it to the pool for next use.

For transaction scope, you want to use the same connection, so you have to do everything in the transaction before that connection is disposed.

so:

using(...){
  call methods execute transaction...

 You can pass the connection into other methods here for use, 
 just make sure it doesn't get disposed in that method.

 commit..
}//connection is disposed.
Kevin
I am using the same connection string. If I have a transaction scope, I do not want to elevate to MSDTC so therefore, I want to be able to reuse the existing connection.
LB
A: 
void SomeMethod(SampleEntities entities){

  var do_dispose = false;

  try{

  if(entities == null) { entities = new SampleEntities();
  entities.Connection.Open(); 
  do_dispose = true; }


    // do with entity object...
  }
  finally{
    if(do_dispose && entities != null){
      entities.Dispose();
    }
  }

}

usage:

using(SampleEntities entities = new SampleEntities()){
  entites.Connection.Open();
  SomeMethod(entities);
  ...
}
Sunny
+1  A: 

You can create a ConnectionScope and DataContextScope using the documents here: http://msdn.microsoft.com/en-us/magazine/cc300805.aspx

This means you can do this:

using (var connection = container.Resolve<IDbConnection>())
using (var context = container.Resolve<IMyDataContext>())
{
    context.Connection = connection;

    // Do some stuff...

    context.SubmitChanges();
}

This is what I've done, and it works a treat! It means that the context.SubmitChanges() is only called at the top of the stack. Therefore allowing you to call methods that use connection/context without worrying about passing them in as parameters.

Neil Barnwell