测试实体框架是否连接到某些东西

测试实体框架是否连接到某些东西

本文介绍了测试实体框架是否连接到某些东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您创建一个新的EntityCollection对象时,连接不会尝试打开数据库,直到您尝试使用该集合执行某些操作。我需要确定一个实体集合是否具有有效的连接,并且我找不到有效的方法。

When you create a new EntityCollection object, the connection doesn't attempt to open the database until you try and do something with that collection. I need to determine whether or not an Entity collection has a valid connection or not, and I can't find an efficient method of doing it.

目前我已经这在我的代码中:

Currently I've got this in my code:

var db = new MyEntityCollection();

try
{
     var checkworking = from c in db.Customers select c;
}
catch
{
     ConnectToBackUp();
}

哪些不仅是可怕的代码,而且很慢,因为它等待一个年龄确定在引发异常之前连接是否处于活动状态。

Which is not only horrible code, but very slow since it waits an age to determine whether or not the connection is active before throwing an exception.

我知道我可以通过使用ConnectionTimeout来控制等待的时间,但这只是另一个丑陋的黑客糟糕的情况更糟糕。

I know I can control how long it waits before giving up by using ConnectionTimeout but that's just another ugly hack that makes a bad situation worse.

确实有更好的方法吗?

推荐答案

通过围绕这些房屋解决这个问题,并建立一个新的连接字符串来测试ADO。仍然涉及使用try catch,但是要快一点:

Solved this by going around the houses a bit and building a new connection string to test with ADO. Still involves using a try catch but it's a lot faster:

    private bool TestConnection()
    {
        EntityConnectionStringBuilder b = new EntityConnectionStringBuilder();
        ConnectionStringSettings entityConString = ConfigurationManager.ConnectionStrings["MyEntityConnectionString"];
        b.ConnectionString = entityConString.ConnectionString;
        string providerConnectionString = b.ProviderConnectionString;

        SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder();
        conStringBuilder.ConnectionString = providerConnectionString;
        conStringBuilder.ConnectTimeout = 1;
        string constr = conStringBuilder.ConnectionString;

        using (SqlConnection conn = new SqlConnection(constr))
        {
            try
            {
                conn.Open();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }

这篇关于测试实体框架是否连接到某些东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:04