Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 511
Tester User Avatar asked Oct 24 '19 08:10

Tester User


People also ask

How does EF core apply migrations?

Migrations are enabled by default in EF Core. They are managed by executing commands. If you have Visual Studio, you can use the Package Manager Console (PMC) to manage migrations. Alternatively, you can use a command line tool to execute Entity Framework CLI commands to create a migration.

What are migrations in EF Core?

The migrations feature in EF Core provides a way to incrementally update the database schema to keep it in sync with the application's data model while preserving existing data in the database.

How to migrate data from one table to another table?

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 t...

Can I drop the database and LET EF create a new one?

You can drop the database and let EF create a new one that matches the model, but this procedure results in the loss of data. The migrations feature in EF Core provides a way to incrementally update the database schema to keep it in sync with the application's data model while preserving existing data in the database.

How to create and update a database with Entity Framework Core?

This post is divided into several parts: Using migrations is a standard way to create and update a database with Entity Framework Core. The migration process has two steps: Creating migration and Applying migration.


1 Answers

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

like image 173
Gibbon Avatar answered Nov 14 '22 23:11

Gibbon