Search code examples
c#entity-frameworkdatabase-migration

Move a column from one table to another along with values using EF migrations


I Have created a new version of my application. I have a database with values and now I would like to move a column from one table in previous version to another with values in the new version using Entity Framework Migrations.

public override void up(){             
     Create.Column("Name").OnTable("Table2");
     Delete.Column("Name").FromTable("Table1");
}

Actual Output:

Table1 in old Version:
    -------------
    |Id   | Name|
    -------------
    |1    | A   |
    -------------
Table2 in old Version:
    -------------
    |Id   | Age |
    -------------
    |1    | 4   |
    -------------
 Table1 in new Version:
    ------
    |Id  | 
    ------
    |1   |
    ------
 Table2 in new Version:
    ------------------
    |Id  | Age | Name|
    ------------------
    |1   | 4   | null|
    ------------------

Expected Output:

Table1 in old Version:
    -------------
    |Id   | Name|
    -------------
    |1    | A   |
    -------------
Table2 in old Version:
    -------------
    |Id   | Age |
    -------------
    |1    | 4   |
    -------------
 Table1 in new Version:
    ------
    |Id  | 
    ------
    |1   |
    ------
 Table2 in new Version:
    ------------------
    |Id  | Age | Name|
    ------------------
    |1   | 4   | A   |
    ------------------

Here I want to create a Name (column) in Table2 from Table1 -> Name along with the values.


Solution

  • I was able to solve the problem by adding a sql statement in migration file before deleting the column in table1.

    public override void up(){             
         Create.Column("Name").OnTable("Table2");
         Execute.Sql("UPDATE table2 Inner join table1 on table2.Id = table1.Id set table2.Name = table1.Name");
         Delete.Column("Name").FromTable("Table1");
    }
    

    Please suggest me if there is any other approach to do this.