Owen
Owen

Reputation: 576

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?

Upvotes: 9

Views: 10366

Answers (2)

Edward
Edward

Reputation: 30056

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

Upvotes: 16

FCin
FCin

Reputation: 3925

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.

Upvotes: 8

Related Questions