EF Database not Connected Exception

348 views Asked by At

I'm using Entity Framework with C# and I need to be able to check weather the database is connected and in case it isn't throw an Exception so the application doesn't crash. Any ideas? thank you!

2

There are 2 answers

0
Antho On

A simple implementation would be something like this

private bool TestConnEF()
{
    using (var db = new DbContext())
    {
        try
        {
            db.Database.Connection.Open();
            if (db.Database.Connection.State == ConnectionState.Open)
            {
                return true;
            }
            return false;
        }
        catch(Exception ex)
        {
            return false
        }
    }
}
0
Salah Akbari On

If the DB connection is valid:

DatabaseContext.Exists();

If a server machine is up, use Ping.Send Method:

Ping.Send Method (String)