Update Database after Model Changes - Entity Framework 7

人盡茶涼 提交于 2019-12-01 03:08:02

问题


I have created an app using the lastest ASP.NET5 MVC 6 Entity Framework 7 and setup migrations using

dnx . ef migration add Initial
dnx . ef migration apply

This works but when I make a change to the model the database is not updated. I would like to have the database automatically update after a model change when I run the program.

My research only points me to old information that doesn't seem to be appropriate to Entity Framework 7.

My current code:

 public ApplicationDbContext(): base()
   {

        if (!_created)
        {

             Database.AsRelational().ApplyMigrations();
             _created = true;         
        }
  }

Can someone point me in the right direction?

I believe it use to work something like this:

Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());

回答1:


You must manually run migrations with EF7 from command line, or call Database.Migrate from code, there is nothing automagic in EF7 (a deliberate decision) and after you change your model, create a new migration




回答2:


There appears to be some confusion between the creation of migrations and the process of updating the database structure.

In EF7, you can no longer automatically generate the migration (the delta between the current database structure and the entity definitions). That HAS to be done at the command line using the "migrations add" command.

Updating the structure of the database, however, can still be done via code. That is done using the dbContext.Database.Migrate() method. You can wire this up in your Startup so that when your app first boots it will ensure your database has been brought up to date with the now-current version of your app.

So your development workflow can be:

  1. modify entity definitions
  2. run "migrations add" command
  3. launch your app*

    • number 3 above assumes you've wired up the Migrate() call mentioned above in your Startup. Otherwise you also have to execute the "database update" command manually.


来源:https://stackoverflow.com/questions/31216983/update-database-after-model-changes-entity-framework-7

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