Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add column with value depending on other column value in entity framework migration

This is my ef migration code ,

   protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<DateTime>(
            name: "ColumnNew",
            table: "MyTableName",
            nullable: true);
    }

So , my new column name is ColumnNew . I already have ColumnOne and ColumnTwo.

My question is, if ColumnOne's value is equal to 1 , I want to copy ColumnTwo's value to ColumnNew .
Can I do this in migration file ?

like image 475
Steven Sann Avatar asked Mar 19 '26 08:03

Steven Sann


1 Answers

You have to add an update statement after creating the new column:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn<DateTime>(
        name: "ColumnNew",
        table: "MyTableName",
        nullable: true);

    migrationBuilder.Sql("UPDATE MyTableName SET ColumnNew = ColumnTwo WHERE ColumnOne = 1");
}
like image 130
Marc Avatar answered Mar 25 '26 04:03

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!