Entity Framework Core - How to check if database exists?

淺唱寂寞╮ 提交于 2020-01-12 06:56:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!