How to check connection to database in Entity Framework Core?

core database-connection entity-framework-core exists

Question

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?

1
4
9/18/2017 5:55:36 PM

Popular Answer

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.).

6
9/18/2017 7:15:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow