C#使用Entity Framework连接SQL Server 2019访问报错排查咨询
SQL Server EF6 连接故障排查
环境信息
- 数据库版本:SQL Server 2019
- 开发技术栈:C# / JSON / XML
现有配置
app.config 配置
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <add name="HDIEntities" connectionString="metadata=res://*/DbTablesDataModel.csdl|res://*/DbTablesDataModel.ssdl|res://*/DbTablesDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=desktopName\SQLEXPRESS;initial catalog=databaseName;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration>
接口查询代码(InfoController)
public class InfoController : ApiController { public HttpResponseMessage GetCountry(int id) { using (HDIEntities entities = new HDIEntities()) { entities.Database.Connection.Open(); var entity = entities.development_index.FirstOrDefault(hdi => hdi.HDI_ID == id); // ID不存在时返回错误信息 if (entity != null) { return Request.CreateResponse(HttpStatusCode.OK, entity); } else { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Country with ID = " + id.ToString() + " not found"); } } } }
数据上下文实现
public partial class HDIEntities : DbContext { public HDIEntities() : base("name=HDIEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public virtual DbSet<development_index> development_index { get; set; } public virtual DbSet<suicide_statistics> suicide_statistics { get; set; } public virtual DbSet<unemployment_rates> unemployment_rates { get; set; } }
故障现象
接口访问时触发连接错误,错误页面截图:
已完成排查项
- 已在SQL Server Configuration Manager确认TCP/IP协议启用正常
- 已完成端口连通性测试
- 已配置Windows防火墙放行SQL Server访问
- 已重装Entity Framework排查依赖损坏问题
排查步骤与解决方案
按优先级从高到低依次验证:
- 修正冗余的手动连接代码
EF6内置连接生命周期管理,不需要手动调用entities.Database.Connection.Open(),这行代码很容易引发连接状态冲突、连接池占用异常,直接删掉这行再测试。 - 校验连接字符串实例名正确性
当前连接字符串中数据源为desktopName\SQLEXPRESS,先打开SSMS登录页确认实际实例名完全匹配:- 如果是默认实例,直接写
(local)即可,不需要带SQLEXPRESS后缀 - 本地调试可以先替换为
.\SQLEXPRESS或者(local)\SQLEXPRESS,排除计算机名解析失败的问题 - 确认服务面板中
SQL Server (SQLEXPRESS)服务处于运行状态
- 如果是默认实例,直接写
- 验证数据库权限
当前使用Windows集成认证(integrated security=True),要确认程序运行身份(调试时为当前Windows用户,IIS部署时为对应应用程序池身份)对目标库databaseName有对应读写权限。可以临时替换为SQL Server账号密码认证测试,快速排除Windows认证的权限问题。 - 检查EDMX元数据完整性
项目采用Database First模式,依赖三个嵌入资源的模型元数据文件:DbTablesDataModel.csdl、DbTablesDataModel.ssdl、DbTablesDataModel.msl。右键项目中的edmx文件重新生成模型,确认三个文件的生成属性为嵌入的资源,排除元数据加载失败引发的连接伪报错。 - 校验发布后配置文件正确性
如果是发布到服务器后报错,检查发布后的配置文件中连接字符串转义是否正常,避免发布转换过程中把"转义为多余字符、或者截断连接参数。
内容的提问来源于stack exchange,提问作者KingSkitz
相关产品推荐
相关产品推荐

