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?
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?
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.
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();