EF: Should I explicitly close database connection when calling OpenConnection manually

c# entity-framework entity-framework-6

Question

In constructor, I open the connection. Think about this code:

public abstract class DataContext : DbContext, IDataContext
{
    static DataContext()
    {
        if (DataContextConfiguration.UseSafePersian)
        {
            DbInterception.Add(new SafePersianInterceptor());                
        }
    }

    private readonly bool _saveChangesOnModify = false;

    protected DataContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
        this.OpenConnection();
    }
   internal void OpenConnection()
        {
            if (((IObjectContextAdapter)this).ObjectContext.Connection.State != ConnectionState.Open)
                ((IObjectContextAdapter)this).ObjectContext.Connection.Open();
        }
    }

When I expressly open a connection, should I then shut it down?

I useEntity Framework variant 6.

UPDATE

I experienced this error, which occurs frequently:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

1
4
12/5/2015 8:41:18 AM

Accepted Answer

Normally, EF automatically establishes and closes connections before/after an operation. But if you manually open a connection, EF won't shut it down for you once a database activity is finished.

If a connection is not needed, it is advisable to cut it off. Additionally, if it's feasible in your circumstance, it's recommended practice for the DbContext to be temporary.

Anyhow, when your DbContext object is disposed of, the connection will be cut off (by the garbage collector for example). But as soon as you're done with it, close it.

Please see the following MSDN page for further details about managing EF connections.

4
1/21/2015 12:35:54 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow