Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Id type of asp.net core 2.2 IdentityUser

I'm new to dot-net core 2.x, so...

I would like to change the type of the Id in asp.net core 2.2 IdentityUser from string to int.

All the examples I've found via google (and the stackoverflow search facility) are giving me examples of asp.net core 2.0 which provides an ApplicationUser when you scaffold Identity (which 2.2 did not provide).

SO, I'm at a loss.. The first thing I tried (which I had high hopes for) was:

services.AddDefaultIdentity<IdentityUser<int>>()
  .AddRoles<IdentityRole>()
  .AddDefaultTokenProviders()
  .AddEntityFrameworkStores<ApplicationDbContext>();

But, I get the following error when I try to Add-Migration InitialCreate -Context ApplicationDbContext:

An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider. Error: GenericArguments[0], 'Microsoft.AspNetCore.Identity.IdentityUser`1[System.Int32]', on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TUser'

Thoughts? Ideas? Documentation I can read?

like image 205
Owen Avatar asked Dec 12 '18 18:12

Owen


2 Answers

For changing IdentityUser key type from string to int, you also need to change the IdentityDbContext to IdentityDbContext<IdentityUser<int>,IdentityRole<int>,int>.

  1. Startup.cs

    services.AddDefaultIdentity<IdentityUser<int>>()
        .AddDefaultUI(UIFramework.Bootstrap4)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
  2. ApplicationDbContext

    public class ApplicationDbContext : IdentityDbContext<IdentityUser<int>,IdentityRole<int>,int>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    }
    
  3. Remove Migrations folder and delete the existing database

  4. Run command to add and update the database

like image 139
Edward Avatar answered Oct 23 '22 19:10

Edward


You can write your own implementation that derives from IdentityUser

public class AppUser : IdentityUser<int> 
{

}

Then register it:

services.AddDefaultIdentity<AppUser>()

This is also useful if you want to add additional properties to your user model.

Remember that because you are changing primary key of the tables, so you will need to recreate these tables instead of updating them.

like image 8
FCin Avatar answered Oct 23 '22 19:10

FCin