Entity Framework Reusing Connection
in the use block to connect to objects,
How do I reuse the connection when calling another method?
so I:
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?
}
}
source to share
You can create ConnectionScope
and DataContextScope
using the following docs: http://msdn.microsoft.com/en-us/magazine/cc300805.aspx
This means that 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 did and it works ... This means it context.SubmitChanges()
is only called at the top of the stack. Therefore, you can call methods that use the connection / context without worrying about passing them as parameters.
source to share
If you are using the same connection string, the connection pool is handled for you.
Even if you use dispose, it doesn't close the connection. It returns it to the pool for next use.
In the area of transactions, you want to use the same connection, so you need to do everything in a transaction before that connection is established.
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.
source to share
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();
}
}
}
using:
using(SampleEntities entities = new SampleEntities()){
entites.Connection.Open();
SomeMethod(entities);
...
}
source to share
A constructor overload DbContext
allows you to determine whether an existing connection should be removed because the context is being removed or not. You need to pass DbConnection
to the context and ask it to keep the connection alive:
using(SqlConnection con = new SqlConnection(conStr))
{
using(var context1 = new SampleEntities(existingConnection:con, contextOwnsConnection:false)
{
}
using(var context2 = new SampleEntities(existingConnection:con, contextOwnsConnection:false)
{
}
}
Change the context to pass params to the base:
class SampleEntities : DbContext
{
public SampleEntities(DbConnection existingConnection, bool contextOwnsConnection) :
base(existingConnection, contextOwnsConnection) )
{
}
}
source to share