In Entity Framework Code first i want to check database is exist before create Database.
In code first when i call Entities dc = new Entities()
then it goes to OnModelCreating and generate Database. How can i check if the Database exists in Entity framework Code first?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can do:
using(var dbContext = new MyContext())
{
if (!dbContext.Database.Exists())
dbContext.Database.Create();
}
Edit:
Following the colegue sugestion, the meaning of this code is very simple: Supose your context constructor is not set to create the database, so before sending any database operations, you can check if it exists, if not, you can create a new one with the connection string parameters being the rules for the creation.