user1968030
user1968030

Reputation:

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

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.

Upvotes: 5

Views: 6367

Answers (1)

Attila Klenik
Attila Klenik

Reputation: 763

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.

Upvotes: 5

Related Questions