简体   繁体   中英

C# Winforms how can I test for SQL connection when using EF6?

I am using Entity Framework 6 as part of my C# Winforms application. My underlying database is SQL Server Express 2014.

I'm trying to test if the DB is there by doing this:

    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();
    }

I currently have this in the 'Load' event of my form, but I understand this doesn't work because the message pumps haven't started yet.

My question is, what is the earliest I can exit (gracefully) if the DB isn't running?

When catching an exception and showing a MessageBox, you should at least leave some time to be able to read the message.

Using the following code will stop the application from closing until you hit "OK".

if (MessageBox.Show("Error message:\n" + ex.Message, "Unable to connect to database!",
                MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
{
     Application.Exit();
}

If all you need is to show a message box then I'd do it just before your main form is created:

public static void Main(string[] args) 
{
    // Test database connection...
    if noConnection
    {
        return;
    }

    // Start the application.
    Application.Run(new Form1());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM