测试实体框架数据库连接

测试实体框架数据库连接

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

问题描述

我有一个通过实体框架连接到MYSQL数据库的应用程序.它可以100%完美地运行,但是我想添加一小段代码,这些代码将在应用启动时测试与数据库的连接.

I have an app that connects to a MYSQL database through the entity framework. It works 100% perfectly, but I would like to add a small piece of code that will test the connection to the database upon app startup.

我的想法是简单地对数据库运行一个微小的命令并捕获任何异常,但是如果出现问题(例如App.Config丢失或数据库服务器关闭),则该应用程序将花费大量时间来运行此代码然后引发异常(〜1分钟).我想这是由于连接超时等导致的,但是我摆弄了这些属性却无济于事.

I had the idea of simply running a tiny command to the database and catching any exceptions, however if there is a problem (eg App.Config missing or Database server down) the app takes a huge amount of time to run this code and then throw the exception (~1 min). I imagine this is due to connection timeouts etc but I have fiddled with such properties to no avail.

任何人都可以对去哪里有任何想法吗?

Would anyone be able to assist with any ideas as to where to go?

推荐答案

您是否只想查看数据库连接是否有效?如果是这样,请查看

Are you just wanting to see if the DB connection is valid? If so take a look at the

using (DatabaseContext dbContext = new DatabaseContext())
{
     dbContext.Database.Exists();
}

http://msdn.microsoft. com/en-us/library/gg696617(v = vs.103).aspx

要检查服务器计算机,数据库服务器或Web服务服务器是否已启动,请尝试以下操作:

and for checking if a server machine is up, DB server or web services server , try this:

public PingReply Send( string hostNameOrAddress )

http://msdn.microsoft.com/en-us/library /7hzczzed.aspx

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

08-01 15:05