如何测试Linq-to-SQL ConnectionString以确保它是有效的

时间:2013-01-24 19:13:19

标签: c# database linq-to-sql connection-string

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

1 个答案:

答案 0 :(得分:1)

将连接字符串中的Connection Timeout设置为低值,如5s。

开放还不够。您可能会得到陈旧的汇集连接。执行查询:SELECT NULL