我正在使用 Linq to SQL并在博客文章中阅读有关尽快关闭数据库连接的信息.作为一个例子,他们展示了一个变量被转换为一个列表(使用.ToList())而不是实际返回Linq查询.我有以下代码: pu
public static bool HasPassword(string userId)
{
ProjDataContext db = new ProjDataContext();
bool hasPassword = (from p in db.tblSpecUser
where p.UserID == userId
select p.HasPassword).FirstOrDefault();
return hasPassword;
}
这个查询好吗?或者数据库连接是否保持打开的时间超过必要的时间?
谢谢你的任何建议
连接将自动管理.但是,有一些(或至少可以像评论所示)与DataContext相关的额外资源.在垃圾收集器销毁DataContext之前,不会释放这些资源.因此,通常最好确保在不再需要DataContext时调用dispose.using (ProjDataContext db = new ProjDataContext()) {
bool hasPassword = (from p in db.tblSpecUser
where p.UserID == userId
select p.HasPassword).FirstOrDefault();
return hasPassword;
}
这里确保在using块退出时调用db.Dispose(),从而显式关闭连接.
编辑:在讨论之后,我自己查看了DataContext配置(也使用了Reflector)并找到了从DataContext.Dispose调用的以下代码(FW 3.5):
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.provider != null)
{
this.provider.Dispose();
this.provider = null;
}
this.services = null;
this.tables = null;
this.loadOptions = null;
}
}
所以有资源被释放:
>可能包含DbConnection,日志(TextWriter)和DbTransaction的提供程序.
> CommonDataServices.
>表字典.
> LoadOptions.
提供者可以保存需要处置的资源(DbConnection和DbTransaction).此外,可能必须处理日志的TextWriter,这取决于用户为DataContext的日志记录机制分配的TextWriter的实例,例如,然后自动关闭的FileWriter.
其他属性保持,据我所知 – 没有太多细节 – 只有内存,但这也可以通过dispose方法用于垃圾收集,但是,它确定何时内存实际被释放.
所以,最后我完全赞同casparOne的声明:
In general, sharing data-access resources like this is a bad idea.
You should create your resources to access the DB, perform your operations, and then dispose of them when done.
