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

使用Entity Framework连接PostgreSQL时遇配置错误求助

解决Entity Framework连接PostgreSQL的配置错误

错误原因分析

  1. 初始System.InvalidOperationException错误:EF无法加载Npgsql提供程序,核心原因是配置中指定的程序集名称过时(旧版包名Npgsql.EntityFramework已被新版Npgsql.EntityFramework6替代),或未正确安装对应依赖包。
  2. 添加<system.data>后出现的ConfigurationErrorsException:该配置节属于.NET Framework内置配置项,无需手动添加,手动配置反而会因版本不兼容或配置逻辑冲突导致识别失败。

解决方案

步骤1:重新安装正确的NuGet包

卸载现有Npgsql相关包,通过NuGet包管理器安装适配EF6的官方包:

Install-Package Npgsql.EntityFramework6

此包会自动安装依赖的Npgsql基础包,并且自动完成app.config的配置工作,无需手动修改配置段。

步骤2:修正app.config配置(若NuGet自动配置失效)

手动替换为以下标准配置:

<?xml version="1.0"?>
<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="DefaultConnection" connectionString="User Id=postgres;Password=pass#123;Host=localhost;Database=db_clients;" providerName="Npgsql" />
    </connectionStrings>
    <entityFramework>
        <defaultConnectionFactory type="Npgsql.NpgsqlConnectionFactory, Npgsql" />
        <providers>
            <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, Npgsql.EntityFramework6" />
        </providers>
    </entityFramework>
</configuration>

关键修正点:

  • 移除手动添加的<system.data>配置段
  • 将entityFramework节点下的provider类型改为Npgsql.NpgsqlServices, Npgsql.EntityFramework6(对应新版包的程序集名称)

步骤3:验证程序集引用

确保项目引用列表中包含以下程序集:

  • Npgsql.dll
  • Npgsql.EntityFramework6.dll
  • EntityFramework.dll
    若引用缺失,右键项目→管理NuGet程序包,重新安装对应包即可自动修复引用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:58:39