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

添加InitialMigration时遇Microsoft.Extensions.Hosting服务访问错误求助

解决Add-Migration InitialMigration执行失败问题

错误核心原因

你遇到两个关键问题:

  1. appsettings.json格式错误:JSON语法不规范,导致配置文件加载失败
  2. DbContext未注册到服务容器:程序启动时未将ApplicationDbContext添加到依赖注入容器,EF Core迁移工具无法创建上下文实例

分步解决方案

1. 修复appsettings.json的格式与连接字符串

你的配置文件存在多层嵌套、语法符号混用问题,按以下标准格式修正:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-DFBVCE0;Database=Employees;User Id=你的数据库账号;Password=你的数据库密码;TrustServerCertificate=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

关键注意事项:

  • 连接字符串参数用分号分隔,禁止混用冒号
  • 移除多余的嵌套大括号
  • 将你的数据库账号和你的数据库密码替换为实际登录信息
  • TrustServerCertificate=True仅用于开发环境跳过证书验证,生产环境建议删除

2. 在Program.cs中注册ApplicationDbContext

打开Program.cs,在添加控制器服务的代码后,新增DbContext注册逻辑:

namespace Employeeproject
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            // 新增:注册ApplicationDbContext到依赖注入容器
            builder.Services.AddDbContext<EmployeesProject.Context.ApplicationDbContext>(options =>
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

            var app = builder.Build();

            // 以下HTTP管道配置代码保持不变
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}

如果尚未安装相关NuGet包,先执行以下命令:

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools

3. 重新执行迁移命令

完成以上修正后,打开包管理器控制台,重新运行:

Add-Migration InitialMigration

内容的提问来源于stack exchange,提问作者Ammad Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:10:21