我有一个使用 Entity Framework 4(ObjectContext) 的旧应用程序。 EF 6 有 DbContext。
在 EF4 中,我可以显式打开数据库连接并执行如下操作
using(var context = new EmployeeContext)
{
context.Connection.Open();
// and then here I am accessing some database objects
// and then calling context.SaveChanes();
}
在其他一些文件中,我也有如下代码。代码没有调用 context.Connection.Open();
using(var context = new EmployeeContext)
{
// here I am accessing some database objects
// and then calling context.SaveChanes();
}
我知道以上两个都可以。应用程序被相当多的用户使用(有时大约有 1200 个并发用户)。
现在我转到我的数据库服务器并在我的应用程序使用高峰期运行下面的查询
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
当时它显示了大约 5000 个打开的连接,这就是我在想的时候;是不是因为 context.Connection.Open() 因为代码没有显式调用 context.Connection.Close() 并且因为这个连接仍然打开并且这增加了数据库服务器的负载。尽管 context.Connection.Open() 包含在 using block 中。
有什么想法吗?
最佳答案
如果你看这段代码
using(var context = new EmployeeContext)
{
context.Connection.Open();
// and then here I am accessing some database objects
// and then calling context.SaveChanes();
}
一旦 context
超出 using 语句的范围,context.Dispose() 就会被调用,这反过来会关闭连接。
显式调用 .Open() 不需要显式调用 .Close(),但您确实希望确保在不再需要打开连接时立即离开 using block 。
关于c# - Entity Framework 4 - 事件连接数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33156234/