Code-First Add-Migration keeps adding the same column

浪子不回头ぞ 提交于 2019-12-05 04:18:42

As it turns out, there is a hidden snapshot of your model in the .designer.cs class associated with your migration. (This is IMigrationMetadata.Target, and is not human-readable.) The series of steps that caused the problem were:

  1. Create changes to the model.
  2. Run Add-Migration to create the migration for the changes. (This creates the hidden IMigrationMetadata.Target value.)
  3. Noticing that there are errors in the way the migration was modelled, change the model class and migration class directly. (The IMigrationMetadata.Target values is now out-of-sync.)
  4. Run Update-Database to apply the changes.

To get out of the mess, create a dummy migration using Add-Migration Dummy, then delete everything from the Up() and Down() methods.

Note that Add-Migration does warn you about this; when you run Add-Migration, it displays:

The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration Dummy' again.

The warning just didn't make any sense until I figured out what the problem was, and saw the hidden IMigrationMetadata.Target value.

Bottom line: don't manually keep your model and migration Up() methods in sync; you have to re-run Add-Migration to set the hidden value correctly.

  1. Copy the migration code into notepad or some text editor
  2. Delete your problem migration that is not working
  3. Add-Migration YourMigrationName
  4. Paste in your migration code that is held in your text editor
  5. Update-Database

This is kind of an ugly work around in my opinion, but it is the only way I have found to make sure my migration has all the changes in it. My guess is Entity Framework makes a migration stale after a certain amount of time so you have to create a new one.

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