ASP.NET Core自定义Identity主键为long时TUser类型约束冲突如何解决
问题根因
该报错是因为Identity服务注册时的泛型参数与你自定义的ApplicationUser、ApplicationRole、主键类型long不匹配,违反了UserStore要求的TUser泛型约束。
解决步骤
1. 修正Identity服务注册逻辑
不要使用默认的
AddDefaultIdentity或普通AddIdentity重载,需要使用适配自定义用户、角色、主键类型的注册方式,.NET 6+的Program.cs示例如下:// 引用所需命名空间 using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using DDM.API.Core.Data.Identity; // 其他命名空间省略... builder.Services.AddIdentity<ApplicationUser, ApplicationRole>(options => { // 此处配置Identity规则,比如密码长度、是否要求唯一邮箱等 }) .AddEntityFrameworkStores<DDMDbContext>() // 显式指定UserStore的所有泛型参数,和你自定义的类型完全匹配 .AddUserStore<UserStore<ApplicationUser, ApplicationRole, DDMDbContext, long, IdentityUserClaim<long>, ApplicationUserRole, IdentityUserLogin<long>, IdentityUserToken<long>, IdentityRoleClaim<long>>>() // 显式指定RoleStore的所有泛型参数 .AddRoleStore<RoleStore<ApplicationRole, DDMDbContext, long, ApplicationUserRole, IdentityRoleClaim<long>>>() .AddDefaultTokenProviders();如果你使用的是.NET 5及更早版本,将上述代码放到
Startup.cs的ConfigureServices方法中即可。2. 移除DbContext中的冗余DbSet声明
IdentityDbContext基类已经内置了角色、用户角色关联等实体的DbSet,删除DDMDbContext中如下两行代码,避免重复声明冲突:public virtual DbSet<ApplicationRole> ApplicationRole { get; set; } public virtual DbSet<ApplicationUserRole> ApplicationUserRole { get; set; }3. 清理旧迁移重新生成
删除之前生成的错误迁移文件,在包管理器控制台依次执行如下命令:
Remove-Migration Add-Migration InitIdentityLongPrimaryKey Update-Database
内容的提问来源于stack exchange,提问作者Olugbenga
相关产品推荐
相关产品推荐

