我需要验证 DataContext 对象上的 ConnectionString 属性,以确保 LINQ 可以获得与数据库的连接。我已经尝试了下面的两种方法,但是,如果连接字符串无效,它们会锁定应用程序。在 LINQ 中还有其他方法可以做到这一点吗?
public static bool TestDBConnection(connectionString)
{
bool result = true;
DomainClassesDataContext db = new DomainClassesDataContext(connectionString);
try
{
// Hangs if connectionString is invalid rather than throw an exception
db.Connection.Open();
// Initially, I was just trying to call DatabaseExists but, this hangs as well if the conn string is invalid
if (!db.DatabaseExists())
{
result = false;
}
}
catch (Exception ex)
{
result = false;
logger.Fatal(ex.Message);
logger.Fatal(ex.StackTrace);
}
finally
{
db.Dispose();
}
return result;
}
最佳答案
将连接字符串中的 Connection Timeout
设置为较低的值,例如 5s。
打开还不够。您可能会得到一个陈旧的池化连接。执行查询:SELECT NULL
。
关于c# - 如何测试 Linq-To-SQL ConnectionString 以确保其有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508944/