Adding a GUID to an existing table in an EF code first migration
The other day I was trying to add a new column to an existing table using Entity Framework Core. The column was supposed to hold a unique GUID for each row. Easier said than done.
After making the appropriate changes to my entity class…
… I ran the add-migration command in the package manager console.
In the migration file generated, I experimented with setting the defaultValue parameter to different takes on a new GUID object. E.g:
But it ended up with EF inserting the same GUID value in all rows when I ran the update-database command. Not very distinct and unique.
After that I tried changing defaultValue to defaultValueSql and setting it to the string value “newId()”.
After that I ran the update-database command in the PM console.
This solved my problem and my table was populated with a new column containing unique GUIDs.