Entity Framework Core - How to check if a database exists?

For EF6, I can check if the database exists as follows:

context.Database.Exists() 

How can I do this in EF Core?

+13
entity-framework-core
source share
3 answers

I found the solution myself:

 (context.GetService<IDatabaseCreator>() as RelationalDatabaseCreator).Exists() 

Works for EF 7.0.0-rc1-final for SqlServer

UPDATE:

Entity Framework Core 2.0:

 (context.Database.GetService<IDatabaseCreator>() as RelationalDatabaseCreator).Exists() 
+32
source share

If you check to see if this exists to determine if you need to create, you can use this:

 context.Database.EnsureCreated(); 
+3
source share

Maybe too late, but what about context.Database.EnsureCreated() ?

A hint pointing to EnsureCreated() in the VS editor reads:

Ensures that the database for the context exists. If it exists, no action is taken...

Also note that the method returns true if the database does not exist, otherwise false . Also, the version of EF Core that I checked is 2.2.6. For newer versions, you may need to check again.

NTN

NB . If you rely on migration, you should avoid this approach, since migrations are not applied when creating databases. For more information, you may need to read this: fooobar.com/questions/295797 / ....

NB (again) : If you need to apply migration, you may need to pay attention to context.Database.CanConnect() . If the test fails (it is assumed that there is no reason other than the existence of the database), you can call context.Database.Migrate() , which applies the migration.

0
source share

All Articles