Search code examples
c#entity-framework-coreef-core-7.0

EF Core migrationBuilder.AlterColumn change existing values


One of my developers has created several new columns on the database as a string. These contain "Yes"/"No" values.

It would be better to convert the columns to a bool.

The Up method on the migrations gives this code

     migrationBuilder.AlterColumn<bool>(
            name: "IsContractor",
            table: "Employee",
            type: "boolean",
            nullable: false,
            oldClrType: typeof(string),
            oldType: "text");

Is there a way when updating the column I can migrate the value i.e.

IsContractor == "Yes"; // will set it to true / false

Solution

  • I would suggest to first add a new column "IsContractorBool" for the boolean value, retaining the old one.

    Then execute something like

    migrationBuilder.Sql(
        @"Update Employee 
          SET IsContractorBool = CASE
              WHEN IsContractor LIKE 'Yes' then true
              ELSE false
          END"
    );
    

    to migrate the data.

    After that you can delete the old text based column and optionally rename column "IsContractorBool" .