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

ASP.NET Core 3 Identity调用FindByEmailAsync报AspNetUsers无效错误

问题描述

在ASP.NET Core 3 Web应用中使用ASP.NET Identity模块时,执行以下用户查询代码抛出异常:

var user = await _userManager.FindByEmailAsync(Input.Email);

抛出的具体错误为:

Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AspNetUsers'。

已提供的项目实现信息

  • 自定义了ApplicationUser模型继承IdentityUser扩展用户字段,代码如下:
public class ApplicationUser : IdentityUser
{
    public string UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNo { get; set; }

    //============Linked Table==================
    [Display(Name = "ব্যাবহারকারীর ধরণ")]
    [ForeignKey("UserType")]
    public int UserTypeId { get; set; }
    public UserType UserType { get; set; }

    [Display(Name = "ব্যাবহারকারীর শাখা")]
    [ForeignKey("Department")]
    public int DepartmentId { get; set; }
    public Department Department { get; set; }

    //============Image Url====================

    [Display(Name = "ব্যাবহার কারীর ছবি")]
    public string UserImageURL { get; set; }
}
  • ApplicationDbContext实现代码如下:
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
    : base(options)
{
}
  • Startup.cs中Identity服务注册代码如下:
services.AddIdentity<ApplicationUser, IdentityRole>()
    // adds UserStore and RoleStore for Usermanager and RoleManager
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultUI()
    // adds a provider that generates unique keys and hashes for things like forgot password links, phone verification etc
    .AddDefaultTokenProviders();
  • 登录、注册页面模型的依赖注入代码如下:
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
private readonly IEmailSender _emailSender;

public LoginModel(SignInManager<ApplicationUser> signInManager,
    ILogger<LoginModel> logger,
    UserManager<ApplicationUser> userManager,
    IEmailSender emailSender)
{
    _userManager = userManager;
    _signInManager = signInManager;
    _emailSender = emailSender;
    _logger = logger;
}
故障原因

报错Invalid object name 'AspNetUsers'本质是程序连接的SQL数据库中不存在Identity框架依赖的AspNetUsers表,结合给出的代码,核心问题有两个:一是ApplicationDbContext没有正确继承Identity专用的上下文类,EF Core无法识别Identity的实体映射规则;二是从未执行EF Core迁移生成Identity所需的相关数据表。

解决方案

按以下步骤操作即可修复:

  1. 修正ApplicationDbContext代码,继承带正确泛型参数的IdentityDbContext,添加业务实体对应的DbSet,重写OnModelCreating应用Identity默认配置,修改后完整代码如下:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<UserType> UserTypes { get; set; }
    public DbSet<Department> Departments { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // 如需自定义Identity表名可在此处配置,默认会生成AspNet前缀的系统表
        // builder.Entity<ApplicationUser>().ToTable("Users");
    }
}

注意:如果仅继承默认DbContext而不是带泛型的IdentityDbContext,EF Core不会自动加载Identity的表结构配置,即使执行迁移也不会生成相关Identity表。

  1. 打开NuGet包管理器控制台,依次执行以下两条命令生成并应用数据库迁移:
Add-Migration InitialIdentitySchema
Update-Database

如果使用.NET Core CLI,在项目根目录执行等效命令即可:

dotnet ef migrations add InitialIdentitySchema
dotnet ef database update
  1. 迁移执行完成后,打开对应SQL Server数据库,确认已生成AspNetUsers、AspNetRoles、AspNetUserRoles等Identity相关表,再运行代码调用FindByEmailAsync就不会再报表不存在的错误。

额外排查点

如果执行完上述步骤仍报错,检查appsettings.json中的数据库连接字符串,确认程序连接的是刚才执行迁移更新的数据库实例,不要连错本地/测试环境的空库。


内容的提问来源于stack exchange,提问作者Md Moseur Rahman Molla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 18:18:37