我需要在LINQ查询后强制执行Dispose吗? [英] Do I need to force a Dispose after a LINQ query?
问题描述
我的DBA表示有太多打开的连接,他认为是.net中的代码使我保持打开状态.
My DBA says that there are way too many connection open and he thinks it is my code in .net that is leaving them open.
我先使用LINQ查询和EF代码.
I am using LINQ querys and EF code first.
示例方法:
public List<Stuff> GetStuff()
{
var db = new DBContext();
var results = db.stuff.toList();
return results;
}
完成后是否需要处置db var?我的理解是,我不需要使用EF和LINQ.请为我提供有关在LINQ/EF和数据库连接的代码或最佳实践中管理连接的Microsoft文档
Do I need to dispose the db var once I am done? My understanding is that I didn't need to in EF and LINQ. Please point me to a Microsoft documentation about managing connection in code or best practices for LINQ/EF and db connections
更新:
我添加了
db.Connection.Close();
db.Dispose();
执行两行之后,我仍然看到SQL中的打开连接.当我强制关闭它时,为什么它不会关闭?
and I still see the open connection in SQL after the two lines were executed. Is there a reason why it wouldn't close when I force it to close?
推荐答案
默认情况下,DbContext自动为您管理连接.因此,您不必显式调用Dispose.
By default DbContext automatically manages the connection for you. So you shouldn't have to explicitly call Dispose.
Blog post on the subject: Link
但是我相信如果您处理大量请求,不进行处理会导致性能问题.您应该添加一条using语句,以查看它是否导致您的情况出现问题.
But I believe not disposing can cause performance issues if you're processing a lot of requests. You should add a using statement to see whether or not it's causing a problem in your case.
这篇关于我需要在LINQ查询后强制执行Dispose吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!