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

Visual Studio2019类库项目DbContext配置异常求助

解决System.Data.Entity.Internal.AppConfig初始化异常(ConfigurationManager加载失败)

核心原因

你遇到的问题是Entity Framework 6(ADO.NET Entity Data Model默认生成EF6代码)在.NET Framework 4.8类库中,无法正确加载System.Configuration.ConfigurationManager程序集——要么是项目没引用该程序集,要么是版本绑定配置缺失;另外类库项目的App.config不会自动生效,必须让主应用程序的配置文件包含连接字符串。


解决方案步骤

1. 添加ConfigurationManager引用

  • 在Visual Studio 2019里,右键你的数据访问层类库项目 → 添加 → 引用
  • 在程序集 → 框架里找到System.Configuration(别选.NET Core版本的包),勾选后确定。
  • 要是找不到框架版的,直接用NuGet安装:打开NuGet包管理器,搜System.Configuration.ConfigurationManager,装一个和.NET Framework 4.8兼容的稳定版本就行。

2. 补全App.config的程序集绑定(可选但建议)

如果装完NuGet包还报错,就在App.config里加程序集重定向配置,确保EF能找到正确版本的ConfigurationManager:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Configuration.ConfigurationManager" 
                          publicKeyToken="cc7b13ffcd2ddd51"
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-你装的版本号" 
                         newVersion="你装的版本号" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <!-- 你的连接字符串配置 -->
  <connectionStrings>
    <add name="YourDbContextName" 
         connectionString="Data Source=你的SQL Server地址;Initial Catalog=数据库名;Integrated Security=True;" 
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

3. 把连接字符串复制到主项目配置文件里

类库的App.config不会被直接读取,必须把连接字符串复制到**引用这个类库的主项目(比如WinForm、Web项目)**的App.config/Web.config里,不然DbContext找不到连接配置。

4. 用.NET Framework适配的DbContext初始化方式

你看到的builder.Services是.NET Core/.NET 5+的配置方式,在.NET Framework 4.8里用不了。EF6在.NET Framework下有两种常用初始化方式:

  • 方式一:通过构造函数传连接字符串名称
public class YourDbContext : DbContext
{
    public YourDbContext() : base("name=YourDbContextName")
    {
    }
}
  • 方式二:直接传连接字符串
public class YourDbContext : DbContext
{
    public YourDbContext() : base(@"Data Source=你的SQL Server地址;Initial Catalog=数据库名;Integrated Security=True;")
    {
    }
}

5. 清理重启再生成

  • 右键解决方案 → 清理解决方案
  • 右键解决方案 → 重新生成解决方案
  • 重启Visual Studio,避免缓存导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 23:04:56