Wednesday, January 30, 2019

When you add one Entity Framework 6 migration and then turn around and have to add another because you realize your column deserves a better name...

Well, you don't really want two migrations back-to-back where a column is added and then removed again do you? Really the two migrations should be cleaned up into one migration. Here is how you do that:

  1. Roll the database back to two migrations ago.
  2. Manually delete the two files which inherit from DbMigration which hold the latest two migrations.
    namespace Peeps.Business.Migrations.Peeps
    {
       using System;
       using System.Data.Entity.Migrations;
       public partial class AddNicknameToContacts : DbMigration
       {
          public override void Up()
          {
             AddColumn("dbo.Contacts", "Nickname", c => c.String());
          }
          
          public override void Down()
          {
             DropColumn("dbo.Contacts", "Nickname");
          }
       }
    }
  3. Create a new migration, making a file like so:
  4. Update the database anew.

The thing NOT to do is to manually doctor up a migration's C# and remove the creation or destruction or both of a column. This will come back to bite you. Entity Framework will end up complaining that it cannot deal with the column somehow in a later migration.

No comments:

Post a Comment