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

ASP.NET Core项目添加IdentityUser时遇实体实例化错误求助

问题解决:ASP.NET Core Identity鉴别器错误

核心问题

你遇到的InvalidOperationException是因为Identity服务配置与自定义用户实体不匹配:你创建了继承自IdentityUser的ApplicationUser,但Program.cs里仍在使用默认的IdentityUser作为Identity的用户类型,导致EF Core无法正确识别实体映射。


具体修复步骤

1. 修正Program.cs中的Identity服务配置

将AddIdentity的泛型参数从IdentityUser改为你的自定义ApplicationUser,让Identity系统明确使用你的扩展用户实体:

builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<DBContext>();

2. 确认DBContext的继承关系

你的DBContext必须继承自IdentityDbContext<ApplicationUser>,而非默认的IdentityDbContext,这样EF Core才能正确映射ApplicationUser的扩展属性:

public class DBContext : IdentityDbContext<ApplicationUser>
{
    public DBContext(DbContextOptions<DBContext> options) : base(options)
    {
    }

    // 已声明的DbSet<ApplicationUser>保留即可
    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
}

3. 调整Register.cshtml.cs中的依赖注入类型

确保注入的UserManager和SignInManager泛型参数为ApplicationUser,而非IdentityUser:

private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly RoleManager<IdentityRole> _roleManager;

public RegisterModel(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, RoleManager<IdentityRole> roleManager)
{
    _userManager = userManager;
    _signInManager = signInManager;
    _roleManager = roleManager;
}

4. 更新数据库迁移

由于实体类型发生变更,需要重新生成迁移并同步到数据库:

# 生成新的迁移文件
Add-Migration UpdateApplicationUserEntity
# 应用迁移到数据库
Update-Database

错误原因说明

当你自定义ApplicationUser继承IdentityUser时,EF Core会使用鉴别器字段区分不同的用户实体类型。但你之前的Identity服务配置仍指向默认IdentityUser,导致系统尝试实例化IdentityUser,却找不到匹配的鉴别器值(数据库中实际存储的是ApplicationUser类型的鉴别器),因此抛出该错误。

内容的提问来源于stack exchange,提问作者Gojko Grubisic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:23:14