EF:我应该在手动调用OpenConnection时显式关闭数据库连接 [英] EF: Should I explicitly close database connection when calling OpenConnection manually

查看:221
本文介绍了EF:我应该在手动调用OpenConnection时显式关闭数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在构造函数中打开连接。
考虑以下代码:

 公共抽象类DataContext:DbContext,IDataContext 
{
static DataContext()
{
if(DataContextConfiguration.UseSafePersian)
{
DbInterception.Add(new SafePersianInterceptor());
}
}

私人只读布尔值_saveChangesOnModify = false;

受保护的DataContext(string nameOrConnectionString)
:base(nameOrConnectionString)
{
this.OpenConnection();
}
内部无效OpenConnection()
{
if((((IObjectContextAdapter)this).ObjectContext.Connection.State!= ConnectionState.Open)
((IObjectContextAdapter )this).ObjectContext.Connection.Open();
}
}

显式打开连接时应该关闭连接吗? / p>

我使用实体框架版本6。



更新



我收到此错误,并且它经常发生:


超时已过期。从池中获得
连接之前,超时时间已过去。这可能是因为所有池化的
连接都在使用中,并且已达到最大池大小。



解决方案

通常,EF在操作完成之前/之后自动打开和关闭连接。但是,如果您手动打开连接,则数据库操作完成后,EF不会为您关闭连接。



最佳做法是在不需要连接时将其关闭。最好还是缩短DbContext的寿命(如果在您的情况下可能的话)。



无论如何,处置DbContext对象时,连接将关闭(例如垃圾收集器)。



有关EF连接管理的更多信息,请参考以下 MSDN 页。


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.

解决方案

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.

这篇关于EF:我应该在手动调用OpenConnection时显式关闭数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆