In normal entity framework I am able to check the database connectivity using dbContext.Database.Exists() but in Entity Framework Core it is not there. What is the alternative of dbContext.Database.Exists() in Entity Framework Core?
-
1Do you mean check connection status ?H. Herzl– H. Herzl2017-09-18 17:57:17 +00:00Commented Sep 18, 2017 at 17:57
-
1I just want to check whether my connection string is valid and It can successfully connect to database.Harsh darji– Harsh darji2017-09-18 18:04:10 +00:00Commented Sep 18, 2017 at 18:04
-
1You can check Status property in connection instanceH. Herzl– H. Herzl2017-09-18 19:03:06 +00:00Commented Sep 18, 2017 at 19:03
3 Answers
You can determine whether or not the database is available and can be connected to with the CanConnect() method:
if (dbContext.Database.CanConnect())
{
// all good
}
You can use CanConnectAsync() for asynchronous operation.
7 Comments
CanConnect() applies to Entity Framework Core 2.2 and 3.0 at the time of this comment. SourceCurrently (up to the latest at this time EF Core 2.0) the DatabaseFacade class (which is the type of the DbContext.Database property) does not expose publicly Exists method.
However, the equivalent of the corresponding EF6 method is provided by the EF Core IRelationalDatabaseCreator service. You can expose it with a custom extension method like this:
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
public static class DatabaseFacadeExtensions
{
public static bool Exists(this DatabaseFacade source)
{
return source.GetService<IRelationalDatabaseCreator>().Exists();
}
}
But please note that the Exists method was never intended to check the database connectivity, but rather than check if the database needs to be created (used internally when you call methods like EnsureCreated, Migrate etc.).
3 Comments
OpenConnection / CloseConnection call pair.The "Exists()" method only check whether the database exists or not, It doesn't really check whether your application can connect to the database or not. For example: if the password is wrong in connection string even then Exists() method will return true. So according to me, a better solution would be open the connection and check if any exception occurs in that.
try
{
dbContext.Database.OpenConnection();
dbContext.Database.CloseConnection();
return true;
}
catch (Exception ex)
{
return false;
}
but if you still want to use Exists() then you can use in this way
dbContext.Database.GetService<IRelationalDatabaseCreator>().Exists();