在实体框架内快速测试数据库连接
[我是 ADO.NET 和实体框架的新手,所以如果这个问题看起来很奇怪,请原谅我。]
在我的 WPF 应用程序中,用户可以在运行时在不同的数据库之间切换。当他们这样做时,我希望能够快速检查数据库是否仍然可用。我可以轻松获得的是 ObjectContext。我正在执行的测试是获取一个非常小的表的总记录数,如果它返回结果,那么它就通过了,如果我得到一个异常,那么它就失败了。我不喜欢这个测试,它似乎是使用 ObjectContext 最简单的测试。
我尝试在连接字符串和 ObjectConntext 中设置连接超时,并且似乎对第一个场景进行了任何更改,而第二个场景已经很快,因此如果它更改了任何内容,则不会引起注意。
场景一
如果在第一次访问之前连接已关闭,大约需要 30 秒才会给出底层提供程序失败的异常。
场景二
如果在我启动应用程序并访问它时数据库已启动,然后在使用测试时连接断开很快并且几乎立即返回。
我希望描述的第一个场景与第二个场景一样快。
请让我知道如何最好地解决此问题,如果有更好的方法来快速测试与数据库的连接,请告知。
[I am new to ADO.NET and the Entity Framework, so forgive me if this questions seems odd.]
In my WPF application a user can switch between different databases at run time. When they do this I want to be able to do a quick check that the database is still available. What I have easily available is the ObjectContext. The test I am preforming is getting the count on the total records of a very small table and if it returns results then it passed, if I get an exception then it fails. I don't like this test, it seemed the easiest to do with the ObjectContext.
I have tried setting the connection timeout it in the connection string and on the ObjectConntext and either seem to change anything for the first scenario, while the second one is already fast so it isn't noticeable if it changes anything.
Scenario One
If the connect was down when before first access it takes about 30 seconds before it gives me the exception that the underlying provider failed.
Scenario Two
If the database was up when I started the application and I access it, and then the connect drops while using the test is quick and returns almost instantly.
I want the first scenario described to be as quick as the second one.
Please let me know how best to resolve this, and if there is a better way to test the connectivity to a DB quickly please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确实没有简单或快速的方法来解决这个问题。实体框架会忽略 ConnectionTimeout 值。我使用的解决方案是创建一个方法,通过传入要验证的位置来检查上下文是否有效,然后从已知的非常小的表中获取计数。如果抛出异常,则上下文无效,否则上下文无效。这是一些示例代码,展示了这一点。
There really is no easy or quick way to resolve this. The ConnectionTimeout value is getting ignored with the Entity Framework. The solution I used is creating a method that checks if a context is valid by passing in the location you which to validate and then it getting the count from a known very small table. If this throws an exception the context is not valid otherwise it is. Here is some sample code showing this.
您可能需要使用 context.Database.Connection.Open()
You may need to use context.Database.Connection.Open()