You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:45:00