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

ASP.NET Core 5 Individual Accounts下找不到AspNetUser类如何解决

.NET 5 MVC Individual Accounts模式下自定义用户实体及角色绑定判断方案
  • 你找不到的AspNetUsers表映射类是ASP.NET Core Identity框架内置的IdentityUser,属于Microsoft.AspNetCore.Identity命名空间,默认不会在项目本地生成实体文件,所有初始身份表都是EF Core基于该内置类生成的,不需要手动反向工程生成该类。
  • 不建议直接通过数据库反向工程工具生成AspNetUsers对应的实体类,生成的平级类会丢失Identity内置的登录、权限、密码哈希等逻辑,导致身份认证模块完全失效。

正确扩展步骤

1. 新增自定义用户实体

在项目实体目录下新建用户类,继承内置IdentityUser,仅补充你手动给AspNetUsers表新增的字段即可:

using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations.Schema;

namespace 你的项目命名空间.Models
{
    public class AppUser : IdentityUser
    {
        // 对应你手动加的游戏角色外键,字段名和数据库保持一致
        public int? GameCharacterId { get; set; }
        
        // 关联游戏角色表的导航属性
        [ForeignKey(nameof(GameCharacterId))]
        public virtual GameCharacter? BoundGameCharacter { get; set; }
    }
}

2. 更新Identity服务配置

找到Startup.cs中的ConfigureServices方法,将默认Identity服务的用户泛型参数替换为你自定义的AppUser:

// 注释掉原有的默认Identity配置
// services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
//     .AddEntityFrameworkStores<ApplicationDbContext>();

// 替换为自定义用户类
services.AddDefaultIdentity<AppUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

再修改数据上下文类ApplicationDbContext,将其继承的泛型上下文替换为对应自定义用户的版本:

// 原默认定义
// public class ApplicationDbContext : IdentityDbContext
// 修改为
public class ApplicationDbContext : IdentityDbContext<AppUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    { }

    // 其他业务表DbSet正常保留,比如游戏角色表
    public DbSet<GameCharacter> GameCharacters { get; set; }
}

3. 同步结构(适配你已手动修改库的场景)

打开包管理器控制台执行迁移命令,因为你已经手动给AspNetUsers表加了外键字段,需要避免EF Core重复执行建字段操作:

Add-Migration AddCustomUserForeignKey

打开生成的迁移文件,把Up和Down方法里自动生成的加字段、删字段代码全部注释掉,再执行更新命令:

Update-Database

这一步只是让EF Core的模型快照和你现有数据库结构对齐,不会修改实际库结构。

4. 实现视图展示逻辑

在控制器中注入UserManager<AppUser>即可获取当前登录用户的绑定状态,传给ViewModel做视图判断:

public class GameController : Controller
{
    private readonly UserManager<AppUser> _userManager;

    public GameController(UserManager<AppUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IActionResult> Index()
    {
        var currentUser = await _userManager.GetUserAsync(User);
        var pageVm = new GameIndexViewModel
        {
            IsCharacterBound = currentUser?.GameCharacterId != null,
            CurrentCharacter = currentUser?.BoundGameCharacter
        };
        return View(pageVm);
    }
}

视图中直接通过ViewModel的属性做条件渲染即可。

关于数据库反向生成实体的说明:EF Core确实支持Scaffold-DbContext命令根据现有库生成实体类,但该方式仅适用于你自己新建的业务表,绝对不要用该命令生成Identity相关的用户、角色、权限表实体,否则会破坏身份认证模块的内置逻辑。


内容的提问来源于stack exchange,提问作者Matěj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:57:22