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

使用EF Core 2连接Ubuntu远程SQL Server失败,求排查方向

问题描述

我正尝试通过Entity Framework Core 2连接部署在Ubuntu上的远程SQL Server,连接字符串配置如下:

"ConnectionStrings": { 
  "DbString": "Server=example.com; Port=1433; Database=EFDB; User Id=SA; Password=FakePassword" 
}

当调用this._context.Database.EnsureCreated();时,出现以下错误:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0]
An unhandled exception has occurred while executing the request
System.TypeLoadException: Could not load type 'Microsoft.EntityFrameworkCore.Infrastructure.RelationalEventId' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.ConfigureWarnings(DbContextOptionsBuilder optionsBuilder)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
at RestApiWithSwagger.Startup.b__4_0(DbContextOptionsBuilder options) in /Users/mrdisaster/dev/RestApiWithSwagger/RestApiWithSwagger/Startup.cs:line 25
...(省略后续堆栈信息)

数据库管理工具如Management Studio、DataGrip等可成功连接该服务器,请问可能是什么问题?

解决方案

这个问题我之前帮人排查过好几次,核心原因几乎都是EF Core相关NuGet包的版本不匹配导致的。EF Core 2.x对组件版本的一致性要求非常严格,Microsoft.EntityFrameworkCore、Microsoft.EntityFrameworkCore.Relational、Microsoft.EntityFrameworkCore.SqlServer这些关联包的版本必须完全一致,否则就会出现这种找不到类型的加载错误。

你可以按照以下步骤来修复:

  • 检查并统一NuGet包版本
    打开你的项目文件(.csproj),查看所有EF Core相关的PackageReference节点,确保它们的版本号都是2.0.0(和你使用的EF Core 2版本对应)。正确的配置应该类似这样:

    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    

    如果发现有版本不一致的情况,直接修改为统一的2.0.0版本即可。

  • 清理NuGet缓存并重新还原
    有时候本地缓存的旧版本包会导致版本冲突,执行以下命令清理缓存并重新还原依赖:

    dotnet nuget locals all --clear
    dotnet restore
    
  • 确认SQL Server Provider包已正确安装
    确保你已经安装了Microsoft.EntityFrameworkCore.SqlServer包,这个是EF Core连接SQL Server的核心组件,它会自动依赖Microsoft.EntityFrameworkCore.Relational,但如果版本不匹配就会触发这个类型加载错误。

另外,既然数据库工具能正常连接,说明你的网络、端口和连接字符串本身是没问题的,不用在这方面浪费时间,重点放在NuGet包版本的一致性上就好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:48:00