Search code examples
c#.netentity-frameworkentity-framework-corecode-first

How do you edit a database migration?


I renamed a few tables and some columns. When I run the Add-Migration command, the migration generates code that drops the old tables and columns and adds ones with the new names. This results in losing the data they contained.

Since I don't want to lose the data, I want to edit the migration, removing the drop and add commands, and replacing them with rename commands.

But after I edit a migration, how do I apply that change?

If I run the Update-Database command, that applies it to the database. But not to the snapshot that Entity Framework maintains of my schema (stored in ApplicationDbContextModelSnapshot).

I need a way to incorporate my edits into the model. How can I accomplish this?


Solution

  • So, this is definitely the messy part of code first.

    As far as the question asked, as GuruStron suggested, the only way I found to have a valid custom migration is to edit it such that the result is the same as what the original, generated migration produced. This keeps it up to date with the database snapshot. And running Update-Database will run your custom update code.

    I think my biggest problem was that I had too many changes going on at once. After struggling with this for a while, I undid some of my changes and added them back bit-by-bit. Entity Framework will rename a table or column if it can figure out that the new name refers to the same column. If it finds many changes, it can't figure this out.

    In the end, I had to customize the migration a little for a couple of columns that were being dropped (customized them to be renamed instead). But I was able to get Entity Framework to rename my tables and other columns.

    The key: make small changes at a time and carefully review the migration before applying them to the database. If you need to customize the migration, do it such that the end result doesn't change.