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

.NET Core 配置ApplicationUser的DbSet后触发IdentityUser识别器匹配错误

错误原因

  • EF Core默认采用**TPH(表 per hierarchy)**策略处理同一张表的实体继承映射:你当前的ApplicationDbContext继承的是无泛型参数的IdentityDbContext,该基类默认已内置DbSet<IdentityUser>声明,你额外新增DbSet<ApplicationUser>后,EF会默认将IdentityUser和ApplicationUser映射到同一张AspNetUsers表,依赖Discriminator字段区分实体类型。
  • 现有数据库中的用户数据Discriminator字段为空/不存在,或者身份验证逻辑尝试实例化IdentityUser对象时匹配不到对应的判别器值,就会抛出该异常。
  • 删掉自定义DbSet<ApplicationUser>后EF不会触发继承映射校验,所以程序可以正常运行,但你自定义的ApplicationUser字段也无法正常使用。

修复方案

  1. 修改ApplicationDbContext的基类为泛型版本的IdentityDbContext<ApplicationUser>,无需手动声明DbSet<ApplicationUser>,基类会自动以你自定义的用户类型作为唯一用户实体,不会触发TPH映射校验:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
  1. 修改项目中身份服务注册的代码,将所有用到IdentityUser的位置替换为ApplicationUser,以.NET 6+的顶层语句为例:
// 原来的写法是AddIdentity<IdentityUser, IdentityRole>(...)
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
  1. 生成并执行新的EF迁移,将自定义字段同步到AspNetUsers表:
# 包管理器控制台命令
Add-Migration AddCustomApplicationUserFields
Update-Database

# 如果用dotnet CLI
dotnet ef migrations add AddCustomApplicationUserFields
dotnet ef database update
  1. 如果之前生成过包含Discriminator字段的迁移,删除该迁移文件后再重新执行上述迁移命令即可。

内容的提问来源于stack exchange,提问作者Sin Lee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 17:36:16