为什么这违反了类型约束?

Jam*_*mes 21 asp.net type-constraints asp.net-identity asp.net-identity-3

我正在尝试自定义ASP.NET Identity 3,以便它使用整数键:

public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }

public sealed class ApplicationRole : IdentityRole<int>
{
  public ApplicationRole() { }
  public ApplicationRole(string name) { Name = name; }
}

public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, ApplicationDbContext, int>
{
  public ApplicationUserStore(ApplicationDbContext context) : base(context) { }
}

public class ApplicationRoleStore : RoleStore<ApplicationRole, ApplicationDbContext, int>
{
  public ApplicationRoleStore(ApplicationDbContext context) : base(context) { }
}

public class ApplicationUser : IdentityUser<int>
{
}

public sealed class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
  private static bool _created;

  public ApplicationDbContext()
  {
    // Create the database and schema if it doesn't exist
    if (!_created) {
      Database.AsRelational().Create();
      Database.AsRelational().CreateTables();
      _created = true;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

编译好了,但随后抛出运行时错误:

System.TypeLoadException

GenericArguments [0],'TeacherPlanner.Models.ApplicationUser','Microsoft.AspNet.Identity.EntityFramework.UserStore`4 [TUser,TRole,TContext,TKey]'违反了类型参数'TUser'的约束.

签名UserStore是:

public class UserStore<TUser, TRole, TContext, TKey>
where TUser : Microsoft.AspNet.Identity.EntityFramework.IdentityUser<TKey>
where TRole : Microsoft.AspNet.Identity.EntityFramework.IdentityRole<TKey>
where TContext : Microsoft.Data.Entity.DbContext
where TKey : System.IEquatable<TKey>
Run Code Online (Sandbox Code Playgroud)

ApplicationUser恰恰是一个IdentityUser<int>.这不是它正在寻找的东西吗?

小智 45

陷入这个问题.它在startup.cs文件上崩溃了.变

services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext,int>()
                .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

声明关键类型似乎已经过了崩溃


Exc*_*ons 9

也遇到了这个问题.我还必须添加IdentityRole键类型,因为它仍然抛出相同的错误.

        services.AddIdentity<ApplicationUser, IdentityRole<int>>()
            .AddEntityFrameworkStores<ApplicationDbContext,int>()
            .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)