Mac下.NET添加连接字符串后执行数据库更新报Internal connection fatal error求助
dotnet ef database update时出现Internal connection fatal error错误 环境信息
dotnet --info .NET SDK (reflecting any global.json): Version: 6.0.412 Commit: ee124f7fe1 Runtime Environment: OS Name: Mac OS X OS Version: 13.4 OS Platform: Darwin RID: osx.13-arm64 Base Path: /usr/local/share/dotnet/sdk/6.0.412/
EF Core数据库上下文配置代码
using System; using Microsoft.EntityFrameworkCore; namespace ConsoleApp2.Data { public class BookStoreContext:DbContext { public BookStoreContext(DbContextOptions<BookStoreContext> options): base(options) { } public DbSet<Books> Books { get; set;} protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=localhost,3306;Database=BookstoreApi;user=root;Password=Rahul@2018; Persist security Info = True;"); base.OnConfiguring(optionsBuilder); } } }
问题现象
执行dotnet ef migrations命令正常,但执行dotnet ef database update时触发错误,错误信息如下:
dotnet ef database update // but is is throwing error.
System.InvalidOperationException: Internal connection fatal error.
at Microsoft.Data.SqlClient.TdsParserStateObject.TryProcessHeader()
at Microsoft.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean& marsCapable, Boolean& fedAuthRequired)
at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover,.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Internal connection fatal error.
错误原因及解决方案
核心问题:数据库类型与驱动不匹配
你代码里用UseSqlServer()指定连接SQL Server,但连接字符串里的端口是3306(MySQL默认端口),账号是root(MySQL默认管理员账号),说明你实际要连接的是MySQL,却误用了SQL Server的EF Core驱动。两种数据库的连接协议不兼容,直接触发内部连接致命错误。
具体解决步骤
更换EF Core数据库驱动
移除SQL Server相关NuGet包,安装适配MySQL的驱动:dotnet remove package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Pomelo.EntityFrameworkCore.MySql --version 6.0.6(版本号需与.NET 6 SDK匹配,选择6.x系列版本)
修改上下文配置代码
将UseSqlServer()替换为UseMySql(),并调整连接字符串为MySQL格式:protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connectionString = "Server=localhost;Port=3306;Database=BookstoreApi;Uid=root;Pwd=Rahul@2018;"; optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)); base.OnConfiguring(optionsBuilder); }重新执行迁移与更新
删除旧的迁移文件(如果已生成),然后重新创建迁移并更新数据库:dotnet ef migrations remove dotnet ef migrations add InitialCreate dotnet ef database update
额外排查点
- 确认本地MySQL服务正常运行,端口3306未被占用
- 检查连接字符串中的账号密码是否正确,确保
root账号有权限访问BookstoreApi数据库 - M1/M2芯片Mac需安装适配arm64架构的MySQL版本
内容的提问来源于stack exchange,提问作者rahulyadav

