gpt4 book ai didi

.net - 测试以查看 Entity Framework 是否已连接到某物

转载 作者:行者123 更新时间:2023-12-03 10:11:22 24 4
gpt4 key购买 nike

当您创建新的 EntityCollection 对象时,连接不会尝试打开数据库,直到您尝试对该集合执行某些操作。我需要确定一个实体集合是否具有有效的连接,但我找不到一种有效的方法来做到这一点。

目前我在我的代码中有这个:

var db = new MyEntityCollection();

try
{
var checkworking = from c in db.Customers select c;
}
catch
{
ConnectToBackUp();
}

这不仅是可怕的代码,而且非常慢,因为它在抛出异常之前等待一段时间来确定连接是否处于事件状态。

我知道我可以通过使用 ConnectionTimeout 来控制它在放弃之前等待的时间,但这只是另一个丑陋的黑客,使糟糕的情况变得更糟。

当然有更好的方法来做到这一点吗?

最佳答案

最简单:

private bool TestConnection()
{
var db = new MyEntityCollection();
int oldTimeOut = db.CommandTimeout;

try
{
db.CommandTimeout = 1;
db.Connection.Open(); // check the database connection
return true;
}
catch
{
return false;
}
finally
{
db.CommandTimeout = oldTimeOut;
}
}

EF6 更新:
using System.Data.Common;
...

public bool TestConnection() {
using (var db = new MyEntityCollection()) {
DbConnection conn = db.Database.Connection;
try {
conn.Open(); // check the database connection
return true;
}
catch {
return false;
}
}
}

关于.net - 测试以查看 Entity Framework 是否已连接到某物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5080360/

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