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

c# entity-framework entity-framework-6

Question

I open connection in constructor. Consider 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();
        }
    }

Should I close connection when I open connection explicitly?

I use Entity Framework version 6.

UPDATE

I got this error and it happens very often:

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

Usually EF opens and closes the connections automatically before/after an operation is completed. However if you open a connection manually, EF will NOT close it for you after a database operation is completed.

It is best practice to close a connection if you don't need it. It's also best practice for the DbContext to be short-lived (if it's possible in your scenario).

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

For more information about EF connection management, please refer to the following MSDN page.

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