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

Why does this violate the type constraint?

我正在尝试自定义 ASP.NET 身份 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;
    }
  }
}

编译没问题,但随后抛出运行时错误:

System.TypeLoadException

GenericArguments[0], 'TeacherPlanner.Models.ApplicationUser', on 'Microsoft.AspNet.Identity.EntityFramework.UserStore`4[TUser,TRole,TContext,TKey]' violates the constraint of type parameter '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>

ApplicationUser 正好是 IdentityUser<int>。这不是它要找的吗?

运行成这个问题。它在 startup.cs 文件上崩溃。 改变了

services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext,int>()
                .AddDefaultTokenProviders();

声明密钥类型似乎可以解决崩溃问题

运行也是这个问题。我还必须添加 IdentityRole 键类型,因为它仍然抛出相同的错误。

        services.AddIdentity<ApplicationUser, IdentityRole<int>>()
            .AddEntityFrameworkStores<ApplicationDbContext,int>()
            .AddDefaultTokenProviders();

EF Core 用户注意事项

补充一下,如果您使用的是 .Net core 3.0(不确定早期版本),则不再有 AddEntityFrameworkStores<TContext,TKey> 方法。

取而代之的是 IdentityDbContext 的通用变体,因此您可以从 IdentityDbContext<TUser,TRole,TKey>

派生 DbContext

例如就我而言

class ApplicationUser : IdentityUser<int> {...}
class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int> {...}

然后在你的启动中你可以使用services.AddDefaultIdentity<ApplicationUser>

摘自 https://github.com/aspnet/Identity/issues/1082

中的最后一条评论