Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Scribbio/6532a88ff70758636bd6460dadde33cc to your computer and use it in GitHub Desktop.
Save Scribbio/6532a88ff70758636bd6460dadde33cc to your computer and use it in GitHub Desktop.
TestEntityFrameworkDBConnection.cs
The following are functions to test whether an application can successfully connect to a database.
<Context> will correspond to the name of the context you wish to test.
// Simplest (EF6):
using System.Data.Common;
...
public bool TestConnection()
{
using (var db = new MyEntityCollection()) {
DbConnection conn = db.Database.Connection;
try {
conn.Open(); // check the database connection
return true;
}
catch {
return false;
}
}
}
Simplest (pre-EF6):
private bool TestConnection()
{
var db = new MyEntityCollection();
int oldTimeOut = db.CommandTimeout;
try
{
db.CommandTimeout = 1; // Change the time out to make this faster (EF required less than a second to detect and start a connection
db.Connection.Open(); // check the database connection
return true;
}
catch
{
return false;
}
finally
{
db.CommandTimeout = oldTimeOut;
}
}
// Here is a more verbose and demonstrative version. It writes connection properties to the console, _
// as well as printing the exception to console,
private static bool TestConnectionEF()
{
using (var db = new TER_SYNAPSE_RCT_Entities())
{
DbConnection conn = db.Database.Connection;
try
{
conn.Open();
if (conn.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 (SqlException ex)
{
throw ex;
}
}
}
You can also make an extension method using one of the above and do something like this:
using Microsoft.EntityFrameworkCore;
using System.Data.Common;
public static class ExtensionMethods
{
public static bool TestConnection(this DbContext context)
{
// test connection
}
}
if (!context.TestConnection())
{
logger.LogInformation("No database connection. Check the connection string in settings.json. {0}", configuration["connectionString"]);
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment