我正在尝试自定义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','Microsoft.AspNet.Identity.EntityFramework.UserStore`4 [TUser,TRole,TContext,TKey]'违反了类型参数'TUser'的约束。< / p>
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>
。这不是它正在寻找的吗?
答案 0 :(得分:45)
陷入这个问题。它在startup.cs文件上崩溃了。 改变
services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
到
services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext,int>()
.AddDefaultTokenProviders();
声明密钥类型似乎已经过了崩溃
答案 1 :(得分:9)
也遇到了这个问题。我还必须添加 IdentityRole 键类型,因为它仍然会抛出相同的错误。
services.AddIdentity<ApplicationUser, IdentityRole<int>>()
.AddEntityFrameworkStores<ApplicationDbContext,int>()
.AddDefaultTokenProviders();
答案 2 :(得分:1)
EF核心用户注意事项
只需在上面添加内容,如果您使用的是.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>
答案 3 :(得分:0)
我现在遇到了同样的问题。修复是不同的。因此在这里张贴。可能会帮助别人。
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext,int>()
.AddDefaultTokenProviders();
我必须为ApplicationRole
继承IdentityRole<int>
创建一个空类。
public class ApplicationRole : IdentityRole<int>
{
}