0

I am trying to customize the ASP.NET identity to use integer based keys instead of string. The code compiles but when I run the app, it throws an error for violation of type constraint. Here's how my identity classes look:

public class AppUser: IdentityUser<int, AppUserClaim, AppUserRole, AppUserLogin>
{
    public DateTime FirstTrip { get; set; }
}

public class AppRole : IdentityRole<int, AppUserRole, AppRoleClaim>
{
}

public class AppUserClaim : IdentityUserClaim<int>
{
}

public class AppRoleClaim : IdentityRoleClaim<int>
{
}

public class AppUserLogin : IdentityUserLogin<int>
{
}

public class AppUserRole : IdentityUserRole<int>
{
}

public class AppUserToken : IdentityUserToken<int>
{
}

My AppDbContext class:

public class AppDbContext: IdentityDbContext<AppUser,AppRole, int, AppUserClaim, AppUserRole, AppUserLogin, AppRoleClaim, AppUserToken>
{
    //other code
}

And here's how I am setting up identity in my startup.cs class:

services.AddIdentity<AppUser, AppRole>(config =>                    //register ASPNET Identity
        {
            config.User.RequireUniqueEmail = true;
            config.Password.RequiredLength = 8;
            config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";     
        })
        .AddEntityFrameworkStores<AppDbContext, int>();                     

When I run the app, I get following error: enter image description here

This setup is in line with some suggestions like:

Why does this violate the type constraint?

ASP.NET identity configuration exception and that breaks dotnet.exe run process

What am I missing?

Community
  • 1
  • 1
user869375
  • 2,299
  • 5
  • 27
  • 46

1 Answers1

0

For anyone running into similar problems, here's what I had to do make it work:

1) Implement custom UserStore and RoleStore to account for changed TKey.

2) Register your custom UserStore and RoleStore in the ConfigureServices method in startup.cs. So Instead of the suggested,

services.AddIdentity<AppUser, IdentityRole>()
        .AddEntityFrameworkStores<AppDbContext, int>();

use the following,

services.AddIdentity<AppUser, IdentityRole>()
        .AddUserStore<AppUserStore<AppDbContext>>()
        .AddRoleStore<AppRoleStore<AppRole, AppDbContext>>();

If you are looking for actual implementation of the custom User and Role store, you can check the following link out(at the very bottom look for PR1):

https://github.com/aspnet/Identity/issues/970

user869375
  • 2,299
  • 5
  • 27
  • 46