Steven Sann
Steven Sann

Reputation: 578

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 ?

Upvotes: 3

Views: 2751

Answers (1)

Marc
Marc

Reputation: 3959

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

Upvotes: 4

Related Questions