Entity Framework Not Creating Database

孤者浪人 提交于 2019-12-02 17:29:09
mazatsushi

Asked around on the MSDN forums instead, and got a satisfactory answer:

Entity Framework will not create a database until first access. The current code block in Application_Start() only specifies the strategy to use when creating the database during first access.

To trigger creation of the database on startup, an instance of the database context must be created, and context.Database.Initialize(true) must be invoked.

I have the same issue and found a elegant solution: call the SetInitializer in the constructor of your DbContext:

public class MyDbContext : DbContext
{
   protected MyDbContext : this("MyConnection")
   {
       Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>());
   }
}

My app setting:

<connectionStrings>
    <add
      name="MyConnection"
      connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\MyDB.mdf;Initial Catalog=MyDB;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

I know this was already answered by mazatsushi in the rightest way. But just to clarify it to begginers: Based in mazatsushi's answer what you have to do is to write:

        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SorteoContext>());
        using (var context = new SorteoContext())
        {
            context.Database.Initialize(force: true);
        }

inside Application_Start() function in Global.asax.cs and Boom! works!

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