Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing an Entity Framework database connection

People also ask

How do you test network connectivity issues to database?

To test the connection to your database, run the telnet hostname port on your Looker server. For example, if you are running MySQL on the default port and your database name is mydb, the command would be telnet mydb 3306 .


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


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

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.


I use this code for my project:

private bool TestConnectionEF()
        {
            using (var db = new SistemaContext())
            {
                try
                {
                    db.Database.Connection.Open();
                    if (db.Database.Connection.State == ConnectionState.Open)
                    {
                        Console.WriteLine(@"INFO: ConnectionString: " + db.Database.Connection.ConnectionString 
                            + "\n DataBase: " + db.Database.Connection.Database 
                            + "\n DataSource: " + db.Database.Connection.DataSource 
                            + "\n ServerVersion: " + db.Database.Connection.ServerVersion 
                            + "\n TimeOut: " + db.Database.Connection.ConnectionTimeout);
                        db.Database.Connection.Close();
                        return true;
                    }
                    return false;
                }
                catch(Exception ex)
                {
                    throw ex;
                }
            }
        }

I used the answer from @Sandor and did an extension method to use with EntityFramework Core.

Here's the code:

using Microsoft.EntityFrameworkCore;
using System.Data.Common;

namespace TerminalInventory
{
    public static class ExtensionMethods
    {
        public static bool TestConnection(this DbContext context)
        {
            DbConnection conn = context.Database.GetDbConnection();

            try
            {
                conn.Open();   // Check the database connection

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

Now you just have to call:

if (!context.TestConnection())
{
    logger.LogInformation("No database connection. Check the connection string in settings.json. {0}", configuration["connectionString"]);

    return;
}

I know this is an old question, but here is my answer for anyone looking for a newer implementation.

I was able to use CanConnect to check the status of the database:

_database.Database.CanConnect();

# Async too
await _database.Database.CanConnectAsync(_cancellationTokenSource.Token);

I hope this helps others as well. Cheers!