fbpx Skip to content

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 my changes to my entity class, 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, 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.

A database column with identical values

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.

A database column with unique values

Author: Magnus Sundström https://magnussundstrom.se