问题
For EF6, I can check whether a database exists in the following way:
context.Database.Exists()
How can I do this in EF Core?
回答1:
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()
回答2:
Probably too late but what about context.Database.EnsureCreated()
?
The tooltip pointing in VS editor at EnsureCreated()
says:
Ensures that the database for the context exists. If it exists, no action is taken...
Note also, the method returns true
is the database does not exist, false
otherwise. Also, the EF Core version I checked this behaviour is 2.2.6. For newer versions you may need to check again.
HTH
NB: If you rely on migrations you should avoid this approach since no migrations are applied when DB is created. For more info you may need to read this: https://stackoverflow.com/a/50005558/1432407.
NB (once again): If you need to apply migrations you may need to pay attention at context.Database.CanConnect()
. If the test fails (supposed no reason other than db existence), you can call context.Database.Migrate()
, which applies the migrations.
来源:https://stackoverflow.com/questions/33911316/entity-framework-core-how-to-check-if-database-exists