Using an Integer as the Primary Key in ASP.Net Core Identity

We generally use auto-increment integers (or serial in the case of Postgres) for our primary keys.
However, by default, the Identity Framework in MVC is set to use string.

In this post, we detail how to change this to work with integers.


First create your custom models for IdentityUser and IdentityRole.
 public class ApplicationUser : IdentityUser<int>
 {

 }
 
 public class ApplicationRole : IdentityRole<int>
 {

 } 


Then update your dbcontext to use your custom models.
 public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
 {
  ...
 }


Finally, we change the configuration of the Identity service in Startup to match.
 public void ConfigureServices(IServiceCollection services)
 {
  ...

  services.AddIdentity<ApplicationUser, ApplicationRole>()
   .AddEntityFrameworkStores<ApplicationDbContext, int>()
   .AddDefaultTokenProviders();

  ...
 }


If you are using migrations, you will need to update them too. If this is a fresh project, simply delete the default migrations and in the package manager console run
Add-Migration CreateIdentity.


In a future post, we will look at replacing SQL Server with Postgres.

Comments

Popular posts from this blog

Demystifying pglogical - Tutorial

Distributed Applications with RabbitMQ and Redis - Part 1