Search code examples
c#asp.net-core.net-coreasp.net-core-mvc

When TwoFactorEnabled is activated, I get an error during login (implementation with Identity)


I have an AccountController that contains all login, register, two-factor and other operations.

I set a status change in the user profile to enable and disable two-step login.

Everything is done correctly until the user activates it and when he tries to login again, he gets an error.

Error:

enter image description here

ArgumentException: Entity type 'IdentityUserToken' is defined with a 2-part composite key, but 3 values were passed to the 'Find' method.

It is better and clearer in the screenshot 👆

Class IdentityDataBaseContext:

    public class IdentityDataBaseContext : IdentityDbContext<User>
{
    public IdentityDataBaseContext(DbContextOptions<IdentityDataBaseContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<IdentityUser<string>>().ToTable("Users", "identity");
        modelBuilder.Entity<IdentityRole<string>>().ToTable("Roles", "identity");
        modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaims", "identity");
        modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims", "identity");
        modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins", "identity");
        modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UserRoles", "identity");
        modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UserTokens", "identity");

        modelBuilder.Entity<IdentityUserLogin<string>>().HasKey(p => new { p.LoginProvider, p.ProviderKey });
        modelBuilder.Entity<IdentityUserRole<string>>().HasKey(p => new { p.UserId, p.RoleId });
        modelBuilder.Entity<IdentityUserToken<string>>().HasKey(p => new { p.UserId, p.LoginProvider });
    }
}

Thank you for helping me to solve this problem ❤


Solution

  • As the error said, you could try following to config 3-part composite key.

    modelBuilder.Entity<IdentityUserToken<string>>().HasKey(p => new { p.UserId, p.LoginProvider,p.Name });