C#C
C#4y ago
16 replies
Pokey

EF Core - Code First - Add new non-null column to existing table with existing data

Hi there,

I would like to add a new non-null column to an existing table which contains existing data. This is a simple Created field, and I want to set it to DateTime.UtcNow for all existing rows.

Of course, if I just add the column and create the migration, this will not work well as the migration will fail with a constraint error.

The common solution I see for this is to add it as a nullable in one migration, populate the data using seeding and then make it non-nullable in another migration.

I don't really want to use seeding, I'd rather just have the migration add it as a nullable column, do some kind of update to set all the missing values then immediately make it non-nullable, all in one migration.

Is this possible? Thanks!
Was this page helpful?