ASP.NET创建API时Add-Migration命令未识别错误求助
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

