For EF6, I can check whether a database exists in the following way:
context.Database.Exists()
How can I do this in EF Core?
I have found the solution on my own:
(context.GetService<IDatabaseCreator>() as RelationalDatabaseCreator).Exists()
It works for EF 7.0.0-rc1-final version for SqlServer
UPDATE:
Entity Framework Core 2.0:
(context.Database.GetService<IDatabaseCreator>() as RelationalDatabaseCreator).Exists()
(context.Database.GetService<IDatabaseCreator>() as RelationalDatabaseCreator).Exists()
using Microsoft.EntityFrameworkCore.Infrastructure;
in my code. Intellisense didnt tells me what i need to do to get GetService()
method.
Jan 9, 2020 at 7:10
UPDATE .Net Core 3.1
To check if a database exists and can be contacted:
dbContext.Database.CanConnect()
SqlException
error if the database does not exist.
Aug 18, 2020 at 11:16
The other solutions tell you whether the database is connectable:
context.Database.GetService<IRelationalDatabaseCreator>().Exists(); //true
context.Database.EnsureDeleted();
context.Database.GetService<IRelationalDatabaseCreator>().Exists(); //true
I want to know whether the database exists:
context.Database.GetService<IRelationalDatabaseCreator>().HasTables(); //true
context.Database.EnsureDeleted();
context.Database.GetService<IRelationalDatabaseCreator>().HasTables(); //false
Note this weird behavior:
context.Database.EnsureDeleted();
context.Database.GetService<IRelationalDatabaseCreator>().HasTables(); //false
context.Database.EnsureCreated();
context.Database.GetService<IRelationalDatabaseCreator>().HasTables(); //true
context.Database.EnsureDeleted();
context.Database.GetService<IRelationalDatabaseCreator>().HasTables(); //true !!
So it's not perfect, but depending on your use case it could be useful.
Exists()
does return false
for me after EnsureDeleted()
is called.
Feb 17, 2022 at 5:58
Entity Framework Core 6.0.7:
dbContext.GetService<IDatabaseCreator>().CanConnect();
works for NpgsqlDatabaseConnector - the Npgsql.EntityFrameworkCore.PostgreSQL 6.0.5 provider and probably for all RelationalDatabaseCreator
descendants since it tests if database really exists as the default/base implmentation.