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

.NET 6中自定义ApplicationUser后无法获取用户数据问题

.NET 6中ApplicationUser无法获取User表扩展字段的解决方案

问题根源

核心错误在于Program.cs中Identity服务注册时使用了默认的IdentityUser,而非自定义的ApplicationUser,导致Identity框架未关联到你的扩展用户类,无法映射表中的新增字段。

修正步骤

1. 修改Program.cs的Identity注册

将AddIdentity的泛型参数从IdentityUser替换为自定义的ApplicationUser:

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// 替换为自定义的ApplicationUser
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
builder.Services.AddTransient<IEmailSender, MailJetEmailSender>();

builder.Services.Configure<IdentityOptions>(opt => 
{
    opt.Password.RequiredLength = 5;
    opt.Password.RequireLowercase=true;
    opt.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(10);
    opt.Lockout.MaxFailedAccessAttempts = 2;
});

2. 更新数据库结构

由于新增了FirstName和LastName字段,需要执行EF Core迁移同步数据库:

  • 终端执行命令:
    dotnet ef migrations add AddUserExtraFields
    dotnet ef database update
    
  • 或Package Manager Console执行命令:
    Add-Migration AddUserExtraFields
    Update-Database
    

3. 可选优化(非必须)

ApplicationDbContext中无需显式声明DbSet<ApplicationUser> ApplicationUser,因为IdentityDbContext<ApplicationUser>已经内置了Users集合,控制器中可直接用_db.Users替代_db.ApplicationUser,效果一致。

验证修正

修改完成后重新运行项目,控制器中通过_db.ApplicationUser(或_db.Users)查询时,即可正常获取FirstName、LastName等扩展字段的数据。

内容的提问来源于stack exchange,提问作者MD SAQUIB RAZA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:57:23