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…
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UniqueId { get; set; }
… I ran the add-migration command in the package manager console.
PM> add-migration MyPurdyMigration
In the migration file generated, I experimented with setting the defaultValue parameter to different takes on a new GUID object. E.g:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "UniqueId",
table: "Orders",
nullable: false,
defaultValue: Guid.NewGuid()); // <-- Generate a GUID as default value
}
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()”.
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "UniqueId",
table: "Orders",
nullable: false,
defaultValueSql: "newId()");
}
After that I ran the update-database command in the PM console.
PM> update-database
This solved my problem and my table was populated with a new column containing unique GUIDs.