Change Primary Key of Users Table in ASP.NET Core Identity

In this tutorial, we will show you how to change the Primary key of the Users table to another type in ASP.NET Core Identity. We will change the Primary key type to int in our example

Before Changing the Primary Key

Changing the Primary Key data type of database, which already has data in it is a big headache. The Problem is bigger if consider changing the PK type of a table that is already in Production.

This tutorial assumes that you are working on a development database.

Change the primary key type

Create a new Project

Create a new ASP.NET Core Web App in VS 2019, with .NET 5.0 & Identity enabled (ASPNetCoreIdentityPK)

Remove the Migration

First, we need to remove the migration.

Context

The ApplicationDbContext inherits from the IdentityDbContext.

Change this to

this

We are specifying int as Primary Key of the IdentityUser table. We also need to change it in IdentityRole table as it is an FK here.

Startup

Change the IdentityUser

to IdentityUser<int>

Update the database

Verify

Change Primary Key type to int in ASP.NET Core

Login Partial

Open the Pages/Shared/_LoginPartial.cshtml and change this

This

Thats it.

Run the App and check

4 thoughts on “Change Primary Key of Users Table in ASP.NET Core Identity”

  1. Hi, I have problem, I do everything from your tutorial and when I open Register or Login Page I receive:
    InvalidOperationException: Unable to resolve service for type ‘Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]’ while attempting to activate ‘RaterestaurantMVC.Web.Areas.Identity.Pages.Account.RegisterModel

  2. Thank you, simple and clear. However, I struggle with extending the IdentityUser with id as int with my own properties in an ApplicationUser. Can you help?

  3. thank you
    but also you must change the _loginPartial like this

    @inject SignInManager<IdentityUser> SignInManager
    @inject UserManager<IdentityUser> UserManager

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top