Question

I am using EF Core to interface with SQL Server. Suppose I add a new nullable property to an existing entity (i.e. a new nullable column to an existing table). How do I get the migration to set the newly added column to a default, non-null value in EXISTING rows in the table?

Suppose I add an int? property to my model. In the scaffolded migration code, I can add a defaultValue argument, like this:

        migrationBuilder.AddColumn<int?>(
            name: "MyNullableInt",
            table: "MyTable",
            nullable: true,
            defaultValue: 0); // Manually added this argument

but, as explained in this SO post,

Keep in mind that if the column is nullable, then null will be the value used for existing rows

And, in fact, a simple experiment shows that the newly added column has a value of NULL in existing rows in the database.

1
1
3/27/2020 5:39:12 AM

Accepted Answer

You can invoke custom SQL during your migration:

migrationBuilder.AddColumn<int?>(...)
migrationBuilder.Sql("UPDATE [dbo].[MyTable] SET [MyNullableInt] = 0");

Please, note: this code and query are not tested! Modify it as appropriate.

2
3/27/2020 5:35:21 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow