Update Database after Model Changes - Entity Framework 7

asp.net-core-mvc asp.net-mvc c# entity-framework entity-framework-core


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)

             _created = true;         

Can someone point me in the right direction?

I believe it use to work something like this:

Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());
7/4/2015 7:17:08 AM

Accepted Answer

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/16/2016 8:16:27 AM

Popular Answer

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.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow