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

ASP.NET Core 8.0 MVC数据库优先模式下添加Identity迁移报错求助

ASP.NET Core 8.0 MVC Identity迁移报错(需指定DbContext)解决建议
  • 显式指定上下文与项目执行迁移命令
    由于你的DbContext位于数据访问层类库项目,创建迁移时必须明确指定上下文类和所属项目,否则EF会默认在启动项目中查找,导致识别失败:

    • Package Manager Console命令:
      Add-Migration InitialIdentity -Context Context1 -Project 你的数据访问层项目名称
    • Dotnet CLI命令:
      dotnet ef migrations add InitialIdentity --context Context1 --project 你的数据访问层项目名称 --startup-project 你的MVC视图项目名称
  • 确认Program.cs中的服务注册配置
    确保在MVC项目的Program.cs中正确关联Identity与你的DbContext,示例代码如下:

    // 注册DbContext
    builder.Services.AddDbContext<Context1>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    
    // 注册Identity并指定使用的DbContext
    builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<Context1>();
    

    注意要正确引用数据访问层中Context1的命名空间,避免类型找不到的问题。

  • 验证DbContext的继承结构
    确认你的Context1正确继承自IdentityDbContext(带正确的泛型参数),示例:

    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore;
    
    namespace 你的数据访问层命名空间;
    public class Context1 : IdentityDbContext<IdentityUser>
    {
        public Context1(DbContextOptions<Context1> options) : base(options)
        {
        }
        // 数据库优先生成的实体DbSet定义
    }
    

    若使用自定义用户/角色类,需替换为对应的泛型参数,比如IdentityDbContext<ApplicationUser, IdentityRole, string>。

  • 清理旧迁移文件
    如果之前尝试生成迁移时产生了错误的Migrations文件夹,先删除数据访问层中的该文件夹,再重新执行迁移命令,避免旧配置残留导致的冲突。

  • 统一NuGet包版本
    检查数据访问层和MVC项目中所有EF Core、Identity相关的NuGet包版本均为8.0.x,版本不一致会导致上下文识别异常。

内容的提问来源于stack exchange,提问作者Ivan Cirimotić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:54:58