Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何测试Linq到SQL连接字符串以确保其有效_C#_Database_Linq To Sql_Connection String - Fatal编程技术网

C# 如何测试Linq到SQL连接字符串以确保其有效

C# 如何测试Linq到SQL连接字符串以确保其有效,c#,database,linq-to-sql,connection-string,C#,Database,Linq To Sql,Connection String,我需要验证DataContext对象上的ConnectionString属性,以确保LINQ可以获得到数据库的连接。我尝试了下面的两种方法,但是如果连接字符串无效,它们会锁定应用程序。在LINQ还有其他方法可以做到这一点吗 public static bool TestDBConnection(connectionString) { bool result = true; DomainClassesDataContext db = new Doma

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

将连接字符串中的连接超时设置为低值,如5s


开放是不够的。您可能会得到一个陈旧的池连接。执行一个查询:
selectnull

它真的挂起了还是只是在倒计时连接超时?啊,可能就是这样。我将立即检查…超时设置为0,但我无法确定如何更改它,因为该属性上只有一个setter。它是由连接字符串设置的<代码>0是“永远的”,所以你可以这样说:)是的,我想我将使用另一种方法来测试Linq使用的连接字符串。这就是它最终的结果。另一个应用程序正在生成此应用程序正在使用的连接字符串,该字符串在连接字符串中设置为0。最后,我不得不解析以将连接字符串替换为5s,并在DataContext上更改它。