我正在使用Entity Framework 6作为我的C#Winforms应用程序的一部分。我的底层数据库是SQL Server Express 2014。
我正试图通过这样做来测试数据库是否存在:
MyEntity me = new MyEntity()
// Try and open the connection, if unable to, show an error message and exit
try
{
me.Database.Connection.Open();
}
catch (SqlException ex)
{
MessageBox.Show("Unable to connect to database!\n\nError message:\n" + ex.Message, "Unable to connect to Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
我目前在我的表单的“加载”事件中有这个,但我知道这不起作用,因为消息泵尚未启动。
我的问题是,如果数据库没有运行,我最早可以退出(优雅地)?
答案 0 :(得分:2)
当捕获异常并显示MessageBox时,您至少应该留出一些时间来阅读该消息。
使用以下代码将停止应用程序关闭,直到您点击"确定"。
A
答案 1 :(得分:1)
如果您只需要显示一个消息框,那么我就在创建主表单之前执行此操作:
public static void Main(string[] args)
{
// Test database connection...
if noConnection
{
return;
}
// Start the application.
Application.Run(new Form1());
}