Reputation: 11905
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.
Upvotes: 1
Views: 548
Reputation: 4002
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.
Upvotes: 2