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

ASP.NET创建API时Add-Migration命令未识别错误求助

解决ASP.NET API中Add-Migration命令未识别的问题

问题描述

执行Add-Migration InitialCreate时触发以下错误:

Add-Migration : The term 'Add-Migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1

具体错误详情:

+ CategoryInfo          : ObjectNotFound: (Add-Migration:String) [], CommandNotFoundException
  + FullyQualifiedErrorId : CommandNotFoundException

同时项目中无Migration文件夹,数据库内也不存在迁移表。

解决步骤

  • 检查EF Core工具是否全局安装
    打开终端执行命令,确认dotnet-ef工具已安装:

    dotnet tool list --global
    

    若未找到,执行全局安装命令:

    dotnet tool install --global dotnet-ef
    
  • 切换到正确的项目目录执行命令
    打开终端,切换到包含DbContext类的项目根目录(而非解决方案根目录),再执行迁移命令。

  • 验证项目引用的EF Core包
    检查项目的.csproj文件,确保包含必要的EF Core包(以SQL Server为例):

    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
    

    缺少的话通过NuGet安装对应包。

  • 改用.NET CLI命令替代PowerShell Cmdlet
    若PowerShell中命令无法识别,直接用.NET CLI执行迁移:

    dotnet ef migrations add InitialCreate
    
  • 确认DbContext配置正确
    确保项目中已创建继承自DbContext的类,且在Program.cs中完成服务注册:

    builder.Services.AddDbContext<YourDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    

完成上述步骤后,重新执行迁移命令即可生成Migration文件夹及对应迁移文件,后续运行dotnet ef database update(或PowerShell的Update-Database)就能创建数据库迁移表。

内容的提问来源于stack exchange,提问作者Vinay Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 07:09:38