Reputation: 576
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
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>
.
Startup.cs
services.AddDefaultIdentity<IdentityUser<int>>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<IdentityUser<int>,IdentityRole<int>,int>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
Remove Migrations
folder and delete the existing database
Run command to add and update the database
Upvotes: 16
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