Question

In my application I want to be able to check to see if the connection to the database failed. If so, I need to know about it immediately. I could just do a try/catch around the first query that is run using LINQ, but I feel there must be a better way. Let's say I have the following chunk of code:

        if (db.DatabaseExists())
        {
             //Do work
        }
        else
        {
            Logger.Error("DB DOWN");
        }

That works and is cleaner, but I have no way of logging WHY the database is down. Knowing LINQ there very well could be some helper function I don't know about that can give me the reason it can't connect without throwing exceptions.

Était-ce utile?

La solution

You can use DataContext.Connection property, Try to open it , if you get an exception then Log the exception, that will give you some information. DataContext.DatabaseExists returns true/false but no other information. You can do it like:

try
{
     //Check if it is not already open
     DataContext.Connection.Open();
}
catch (SqlException sEx)
{
    //Log sEx
}
catch (Exception ex)
{
    // log ex
}
finally
{
    if (DataContext.Connection != null && DataContext.Connection.State == ConnectionState.Open)
    {
        DataContext.Connection.Close();
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top