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

如何在C#代码中正确执行dotnet ef scaffold命令

执行失败核心原因
  • 调用CMD.exe时未添加/c参数:CMD默认不会执行传入的命令字符串,启动后会直接退出,后续的dotnet ef指令根本不会被触发
  • 未指定正确的工作目录:自启动进程的默认工作目录通常是程序运行的bin目录,和Visual Studio包管理器控制台默认定位到项目根目录的上下文不一致,找不到项目csproj文件、dotnet-ef工具无法关联正确的项目环境
  • 原代码中输出目录参数存在拼写错误:ModelsFolderNam缺失末尾字符,应为ModelsFolderName
可直接运行的正确实现

推荐直接调用dotnet进程,不需要依赖CMD,跨平台兼容性更好,也省去CMD参数配置的坑:

var processStartInfo = new ProcessStartInfo
{
    FileName = "dotnet",
    Arguments = @"ef dbcontext scaffold ""server=xxx.xxx.x.xxx;user=xxxxx;database=dbname;port=3306;Password=xxxxx;Allow User Variables=True;"" Pomelo.EntityFrameworkCore.MySql -t customers -o ModelsFolderName",
    // 替换为你的EF Core项目csproj文件所在的绝对路径
    WorkingDirectory = @"C:\YourSolutionPath\YourEfCoreProjectDirectory",
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    UseShellExecute = false,
    CreateNoWindow = true
};

using var process = Process.Start(processStartInfo);
// 读取执行日志和报错信息,方便排查问题
string runOutput = process.StandardOutput.ReadToEnd();
string runError = process.StandardError.ReadToEnd();
process.WaitForExit();

// 调试时可打印输出查看执行结果
// Console.WriteLine(runOutput);
// if (!string.IsNullOrEmpty(runError)) Console.WriteLine(runError);

如果一定要通过CMD调用,只需要把FileName改为cmd.exe,Arguments最前面加上/c 即可,其余配置保持不变。

前置校验项
  • 运行环境已安装和项目EF Core版本匹配的dotnet-ef工具,可在终端执行dotnet ef --version验证
  • 连接字符串配置、Nuget包版本和你在包管理器控制台能跑通的环境完全一致
  • 执行程序对目标项目的Models文件夹有写入权限

内容的提问来源于stack exchange,提问作者khaled saleh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 21:45:45