Search code examples
asp.net-coreentity-framework-coredatabase-migrationentity-framework-migrations

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?


Solution

  • 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)");
    }