ColmanJ
ColmanJ

Reputation: 456

Handle DbContext creation exception

In normal conditions there are no problems, but when the database can't be found visual studio shows that SQLExceptions are thrown and being caught.

I tried to wrap the creation of the DbContext but it never gets to the catch and keep stuck at the new MyDbContext().

MyDbContext db = null;
try
{
    db = new MyDbContext ();
    myData = db.MyData.ToList (); // myData defined earlier
}
catch (System.Data.Entity.Core.EntityException ) // I tried to catch System.Exception with the same result
{
    MessageBox.Show ("Can't connect to server.");
    return;
}
finally
{
    db?.Dispose ();
}

So is there any way to catch the exceptions thrown or to catch that the connection couldn't be established?

To test the bad connection I'm changing the connectionstring Data Source to something like Localhost1.

Upvotes: 2

Views: 1601

Answers (1)

ColmanJ
ColmanJ

Reputation: 456

So after waiting a long while and seeing exceptions thrown internally a couple of times, the System.Data.SqlClient.SqlException is eventually thrown outside and your able to catch it.

If you change the authentication of the connection string then an exception is thrown almost immediately, so it's probably trying to contact the data source multiple times before giving up and forwarding the exception.

Upvotes: 1

Related Questions