Entity Framework Code First check Database exist

▼魔方 西西 提交于 2019-12-08 09:31:35

问题


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.




回答2:


This would be a static alternative, that works even without creating the DbContext first:

    System.Data.Entity.Database.Exists(dbNameOrconnectionString);


来源:https://stackoverflow.com/questions/19920444/entity-framework-code-first-check-database-exist

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