Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core - How to check if database exists?

For EF6, I can check whether a database exists in the following way:

context.Database.Exists()

How can I do this in EF Core?

like image 551
Don Tomato Avatar asked Nov 25 '15 08:11

Don Tomato


People also ask

How do I check if a database exists?

In creating a database you also need to check whether or not the database already exists. In order to do so, simply use the 'if exists' method and select the name of the database from sysdatabases.

Which command is used to verify if the database is created or not?

Verify Databases. Once you have run the create database command, you can check if the databases are created or not by using the following command: db2 list db directory.


3 Answers

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() 
like image 73
Don Tomato Avatar answered Sep 20 '22 23:09

Don Tomato


UPDATE .Net Core 3.1

To check if a database exists and can be contacted:

dbContext.Database.CanConnect() 
like image 22
flip Avatar answered Sep 23 '22 23:09

flip


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.

like image 32
lonix Avatar answered Sep 19 '22 23:09

lonix