Reafidy
Reafidy

Reputation: 8481

Update Database after Model Changes - Entity Framework 7

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>());

Upvotes: 5

Views: 10112

Answers (2)

ErikEJ
ErikEJ

Reputation: 41819

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

Upvotes: 6

retsvek
retsvek

Reputation: 395

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.

Upvotes: 3

Related Questions