我需要验证 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;
}