Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update data in existing column with EF Core Migration

My table in SQL has two fields: Id and Status. It looks something like this

ID | Status

1 | "Status1"

2 | "Status2"

I should make a migration that will change those status values into those that I want? How can I achieve this?

like image 883
private7 Avatar asked Feb 19 '20 12:02

private7


People also ask

How do I update my database in migration?

After creating a migration file using the add-migration command, you have to update the database. Execute the Update-Database command to create or modify a database schema. Use the –verbose option to view the SQL statements being applied to the target database.

How do I add a migration to a specific DbContext?

One way to create multiple migration sets is to use one DbContext type per provider. Specify the context type when adding new migrations. You don't need to specify the output directory for subsequent migrations since they are created as siblings to the last one.


1 Answers

I should make a migration that will change those status values into those that I want?

Try add SQL statements into Up method of the generated migration file manually like below

protected override void Up(MigrationBuilder migrationBuilder)
{
        migrationBuilder.Sql("UPDATE A SET AName = 'Jhon' WHERE Id=3");
}

For updating multiple records , you could refer to the following code

protected override void Up(MigrationBuilder migrationBuilder)
{
        migrationBuilder.Sql(
           "UPDATE A SET AName = CASE Id " +
                   "WHEN 1 THEN 'Shariy' " +
                   "WHEN 2 THEN 'Mary'" +
                   "ELSE AName END " +
                   "WHERE Id IN(1,2)");
}
like image 154
Xueli Chen Avatar answered Oct 19 '22 01:10

Xueli Chen