gpt4 book ai didi

c# - 我的数据库连接关闭了吗? (Linq to Sql)

转载 作者:太空狗 更新时间:2023-10-30 00:36:18 29 4
gpt4 key购买 nike

我正在使用 Linq to SQL 并阅读了一篇关于尽快关闭数据库连接的博文。例如,他们展示了一个变量被转换为列表(使用 .ToList())而不是实际返回 Linq 查询。我有以下代码:

 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 block 退出时调用 db.Dispose(),从而显式关闭连接。

编辑: 在讨论之后,我自己查看了 DataContext dispose(也使用 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

提供者可能持有需要释放的资源(DbConnectionDbTransaction)。此外,可能必须处理日志的 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.

关于c# - 我的数据库连接关闭了吗? (Linq to Sql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2352268/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com