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

ASP.NET Identity自定义ApplicationUser无法使用指定数据表问题排查

问题描述

已自定义ApplicationUser并在Identity存储、UserManager等组件中使用,但系统始终尝试读取AspNetUsers表,而非迁移生成的ApplicationUser表。即使清空AspNetUsers表保留ApplicationUser表,使用UserManager<ApplicationUser>时仍从AspNetUsers拉取数据。

相关代码如下:

Program.cs

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddSignInManager<SignInManager<ApplicationUser>>()
        .AddRoles<IdentityRole>()
        .AddRoleManager<RoleManager<IdentityRole>>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<CoreContext>();

ApplicationUser.cs

public class ApplicationUser : IdentityUser<string>
{
    public int? TestValue { get; set; }
}

HomeController 相关代码

构造函数

public HomeController(UserManager<ApplicationUser> userManager)
{
    _userManager = userManager;
}

Index方法

public async Task<IActionResult> Index()
{
    var test = _userManager.Users.ToList();
    var user = await _userManager.FindByEmailAsync("testnew@email.com");   //user exists in SQL table

    return View();
}

解决方案

问题根源是EF Core Identity默认沿用AspNetUsers作为用户表名,即便自定义了ApplicationUser,未显式配置表名的话,EF Core仍会使用默认命名。按以下步骤修复:

  • 在DbContext中配置表名映射
    打开CoreContext类,重写OnModelCreating方法,明确指定ApplicationUser对应的表名:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        
        // 绑定ApplicationUser到目标表
        modelBuilder.Entity<ApplicationUser>().ToTable("ApplicationUser");
        
        // 若有自定义角色表,可同步配置
        // modelBuilder.Entity<IdentityRole>().ToTable("ApplicationRole");
    }
    
  • 重新生成并执行迁移
    旧迁移是基于默认表名生成的,需更新迁移以应用新配置:

    1. 打开包管理器控制台,执行:
      Add-Migration UpdateUserTableName
      
    2. 执行迁移更新数据库:
      Update-Database
      
  • 检查Identity配置一致性
    确认所有Identity相关服务(如AddDefaultIdentity、AddEntityFrameworkStores)都使用了ApplicationUser和CoreContext,避免代码中意外引用IdentityUser而非自定义的ApplicationUser。

  • 清理旧表(可选)
    迁移完成后,数据库会生成ApplicationUser表,可删除旧的AspNetUsers表,避免后续混淆。

内容的提问来源于stack exchange,提问作者Jacob Schroeder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:30:08