21

我正在尝试自定义 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;
    }
  }
}

这可以编译,但随后会引发运行时错误:

System.TypeLoadException

GenericArguments[0], 'TeacherPlanner.Models.ApplicationUser', on '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>

ApplicationUser正是一个IdentityUser<int>. 这不是它要找的吗?

4

3 回答 3

45

遇到了这个问题。它在 startup.cs 文件上崩溃。改变了

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

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

声明密钥类型似乎克服了崩溃

于 2015-05-04T11:26:47.833 回答
9

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

        services.AddIdentity<ApplicationUser, IdentityRole<int>>()
            .AddEntityFrameworkStores<ApplicationDbContext,int>()
            .AddDefaultTokenProviders();
于 2016-01-09T20:13:43.687 回答
2

EF Core 用户注意事项

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

相反,有一个通用变体,IdentityDbContext而是您从 DbContext 派生IdentityDbContext<TUser,TRole,TKey>

例如在我的情况下

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

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

摘自https://github.com/aspnet/Identity/issues/1082中的最后一条评论

于 2019-11-02T18:15:22.407 回答