Testing an Entity Framework database connection

In EntityFramework Core you can simply call: Database.CanConnect();.

(using EF Core 2.2.1)

Summary: Determines whether or not the database is available and can be connected to.

Note that being able to connect to the database does not mean that it is up-to-date with regard to schema creation, etc.


The solution as @Danilo Breda pointed out is to call the DbContext.Database.Connection.Open()

It is tested with EF6.

My implementaion:

    public static bool CheckConnection()
    {
        try
        {
            MyContext.Database.Connection.Open();
            MyContext.Database.Connection.Close();
        }
        catch(SqlException)
        {
            return false;
        }
        return true;
    }

Are you just wanting to see if the DB connection is valid? If so take a look at the

using (DatabaseContext dbContext = new DatabaseContext())
{
     dbContext.Database.Exists();
}

http://msdn.microsoft.com/en-us/library/gg696617(v=vs.103).aspx

and for checking if a server machine is up, DB server or web services server , try this:

public PingReply Send( string hostNameOrAddress )

http://msdn.microsoft.com/en-us/library/7hzczzed.aspx