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