EF Core move column data from table to another while migration (UP)

c# ef-migrations ef-model-builder entity-framework-core

Question

I updated my data model by removing a column from a table to another, but I hava data in this column

To do that, I started by adding the new column in the new table and its done.

Now I want to migrate column data from the old table to the new one, I'm thinking to do it in the Up(MigrationBuilder migrationBuilder) method but I don't know the right approach.

So, I'm asking if anyone knows from where I can start.

Thank you all!

1
0
10/24/2019 8:41:51 AM

Accepted Answer

Within the Up() Method of the migration you can write custom SQL using the migrationBuilder.Sql() function - this is generally the way that I would handle data being migrated from one column to another or in this case across tables.

Bear in mind of course that things are executed in an order, so you would need the sql to run between the column being added and the other being dropped.

Equally for safety sake and keeping things backwards compatible in the Down() side of things you should also include the sql that does the reverse so that you can always roll back later

1
10/24/2019 8:47:57 AM

Popular Answer

For example, we have table A and table B.

In my projects, I follow three-step procedure:

  1. Create migration to add new column to table B (in Up() part). In Down() part I add code to delete this column in table B.
  2. Create migration to transfer data from table A to table B (in Up() part). In Down() part I add code to transfer data from table B to table A.
  3. Create migration to delete column in table A (in Up() part). In Down() part I add code to create column to table A.


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow