c# - 如何测试 Linq-To-SQL ConnectionString 以确保其有效

标签 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;
    }

最佳答案

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

打开还不够。您可能会得到一个陈旧的池化连接。执行查询:SELECT NULL

关于c# - 如何测试 Linq-To-SQL ConnectionString 以确保其有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508944/

相关文章:

c# - 如何从包含 5000 条记录的 Excel 文件插入到 documentDB?

c# - 如何使用 webservice C# 将数据从数据库发送到客户端

c# - 在 ASP.NET 动态数据中的单元格上插入自定义值

.net - Linq to SQL - 返回前 n 行

c# - .GetValueNames() 方法的空引用异常

c# - 使用 HTMLAgilityPack 和 XPath 获取 childNodes 的问题

c# - IEnumerable : Get all before the last that matches a predicate

php - 使用 Laravel Eloquent 地按月或周分组

c# - 如何使用 ASP.net 3.5 和 LINQ 将数据库分层数据转换为 XML

c# - 使用 jQuery AJAX 缩短 Web 方法中的参数数量