Update existing database with Entity Framework Code First in MVC

早过忘川 提交于 2019-11-28 08:40:08

Why did you do steps 1-4? That's where you went wrong. If you had a previously generated database and you're just making changes to the schema, then just generate a migration and apply it. By doing steps 1-4, you're effectively undoing Entity Framework's knowledge of this database and essentially ending up with code-first with an existing database. At which point, you either have to manually change your schema or let Entity Framework blow it out and start over.

As far as getting back to a state where you can apply migrations again goes, you were on the right track with generating a migration and just emptying out the Up method. However, you need to do this against your application's previous state, i.e. the one that matches the database as it currently is. Otherwise, Entity Framework is going to generate create tables that include your code changes. So the steps to follow are:

  1. Revert your code to the point before you started modifying your POCOs.
  2. Generate a migration.
  3. Remove everything in the Up method
  4. Apply the migration with update-database
  5. Re-apply the changes you made to your POCOs.
  6. Generate another migration (this one should now just have add/alter column statements instead of create tables)
  7. Apply the migration.

After that, you should be good to go again. Then, the next time you make code changes, just follow steps 5 & 6.

I've had this exact problem. Seems It is worth noting that there are commands in place to aid in this situation, namely the -IgnoreChanges and -Force flags.

I was trimming from a multi-dbContext to single dbContext app. As you can guess the tables already existed, but the single context new nothing of the tables that were maintained in the second context.

It is actually quite simple (albeit 2 days of searching for the answer to no avail led me to read up on the command lines of EF Code First Migrations and the package manager...) Here is how I handled it.

You could delete migrations folder and _Migrations Table in SQL… this would then cause you to need to use the following: Enable-Migrations -Force

But you should be able to pick up from here without taking drastic measures:

  1. Add-migration “Reset” –IgnoreChanges –Force (Forcibly ignores changes that may exists in your model/class – good for getting started with existing database)
  2. Update-Database (just writes migration line as a basis)
  3. Add-migration “AddMyMigrationsToThisDb” –Force (forcibly iterates object model in code to pick-up changes)
  4. Update-Database

Now you should be back on track for just using Add-Migration and Update-Database without the extra flags.

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