Change the Primary Key Type in Entity Framework

April 18, 2020

Imagine that you’ve created a Primary Key in Entity Framework (AFAIK, this applies to EF Core and EF 6), and it’s the wrong type: perhaps you created it as a Guid and decided it should be a string; obviously, if you created it as a string and you want it as an integer, then you have the same issue you have with any such change: EF doesn’t know how to change the text “Donald” into an integer any more than you do !

The Problem

Imagine you have a primary key PK_Duck on the table: Duck. The table has the following data:

Id

Name

Description

80c983c9-14d0-49b7-889d-a08b874d4629

Donald

White with a blue coat

5f2178fa-2605-4f70-bdfd-a7f6e924aab0

Jemima

White with a bonnet and shawl

If you just change the model / entity type from a Guid to a string, EF will generate something like the following migration:



migrationBuilder.AlterColumn<string>(
                name: "Id",
                table: "Duck",
                nullable: false,
                oldClrType: typeof(Guid));

If you try to update the DB, you’ll get the following error:

The object ‘PK_Duck’ is dependent on column ‘Id’. ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column.

The Solution

The solution here is actually quite straightforward, and exactly what you would do in raw SQL; you just drop the primary key. Manually change the migration to drop the key first, and then re-create it afterwards:



migrationBuilder.DropPrimaryKey("PK\_Duck", "Duck");

migrationBuilder.AlterColumn<string>(
                name: "Id",
                table: "Duck",
                nullable: false,
                oldClrType: typeof(Guid));

migrationBuilder.AddPrimaryKey("PK\_Duck", "Duck", "Id");




Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024