Update existing database with Entity Framework Code First in MVC

前端 未结 2 1761
暗喜
暗喜 2020-12-09 12:23

In my MVC application I used Entity Framework 6 and created database with code first approach. After a certain time, I updated one of the entity classes by adding new column

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 12:49

    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.

提交回复
热议问题