Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

How to Make a Field an Identity Field - EF Core 3

RSS
Modified on Wed, Dec 23, 2020, 11:46 AM by Administrator Categorized as EF Core, Entity Framework Code First

Overview

The code that is automatically generated by EF Core by way of the "Add-Migration" command will not run successfully against the database. This article presents a code pattern for what it needs to manually be replaced by.

Auto-Generated Code

This is the code that is automatically generated via the "Add-Migration" command

migrationBuilder.AlterColumn<int>(
    name: "Id",
    table: "PrimaryKeyTable",
    nullable: false,
    oldClrType: typeof(int),
    oldType: "int")
    .Annotation("SqlServer:Identity", "0, 1");

Manual Refactoring

The above code needs to be replaced by the following code

/* Add new identity column */
migrationBuilder.AddColumn<int>(
    name: "NewId",
    table: "PrimaryKeyTable",
    nullable: false
    )
    .Annotation("SqlServer:Identity", "1, 1");

/* Remove foreign keys against the old PK field */
migrationBuilder.DropForeignKey(
    name: "FK_ForeignKeyTable_PrimaryKeyTable_RaceId",
    table: "ForeignKeyTable"
    );

/* Drop Primary Key */
migrationBuilder.DropPrimaryKey(
    name: "PK_PrimaryKeyTable",
    table: "PrimaryKeyTable"
    );

/* Drop Old Column */
migrationBuilder.DropColumn(
    name: "Id",
    table: "PrimaryKeyTable"
    );

/* Rename New Column*/
migrationBuilder.RenameColumn(
    name: "NewId",
    table: "PrimaryKeyTable",
    newName: "Id");

/* Add Primary Key back */
migrationBuilder.AddPrimaryKey(
    name: "PK_PrimaryKeyTable",
    table: "PrimaryKeyTable",
    column: "Id"
    );

/* Add Foreign Keys back */
migrationBuilder.AddForeignKey(
    name: "FK_ForeignKeyTable_PrimaryKeyTable_RaceId",
    table: "ForeignKeyTable",
    column: "RaceId",
    principalTable: "PrimaryKeyTable",
    principalColumn: "Id",
    onDelete: ReferentialAction.Restrict
    );

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2021, Patrick Jasinski.