Search code examples
entity-frameworkcode-firstentity-framework-migrationsseeding

Fill a new colum from another columns before I delete them during migration


I am using Entity Framework - Code First. The databse is already filled. I must add a colum to a table and remove two others columns. The new colum will be filled with a merge of the old columns. I am trying to use migrations and the seed method.

I resume my task:

  1. Add a column in a table;
  2. Fill the new column with data from two other columns;
  3. Delete the other two columns.

Here my migration:

public partial class MyNewMigration : DbMigration
{
    public override void Up()
    {
        AddColumn("customers.myTable", "newCol", c => c.String());
        DropColumn("customers.myTable", "oldCol1");
        DropColumn("customers.myTable", "oldCol2");
    }

    public override void Down()
    {
        AddColumn("customers.myTable", "oldCol1", c => c.String());
        AddColumn("customers.myTable", "oldCol2", c => c.String());
        DropColumn("customers.myTable", "newCol");
    }
}

Do I must add the code to fill the new column inside the Up method?


Solution

  • Do I must add the code to fill the new column inside the Up method?

    Yes, you need to transform your data! and maybe you will need Sql functions or a stored procedures in a complex data transformation.

    For example you can do in your migration file:

    AddColumn("customers.myTable", "newCol", c => c.String());
    Sql("UPDATE customers.myTable SET newCol= ''");
    

    or

    Sql("Update customers.myTable SET newCol = oldCol1+ oldCol2");
    

    As I mentioned before, if you need a complex data tranformation, you have to use stored procedures or functions with input/output parameters and you have first to add them and then will be able to use them them with the Sql command.

    Alternativly you can use the Migration Seed. Seed method is called between each migration level, for example if you have migration levels 1, 2, 3 then it will be called 3 times. The problem of the seed method, you have to build your migrations logic for all migrations levels in one file. You can use switch case or if else and then check in which level you are. If you are in level 1 then you can add the code logic for migration level 1 and if you are in level 2 then you have to add the code for level 2 et. This apporach is for me not clean and if you want to use it then use it with a Factory Pattern with allow to sperarte the Code for each migration level (SRP). Both apporachs do the same it depends on you.