配置 npgsql 以与 .NET 3.5 和 EF 一起使用

Configure npgsql to use with .NET 3.5 and EF

我正在开发一个应用程序,该应用程序使用与 .NET Framework 3.5(不是更新版本)一起工作的第三方库。我的应用程序是 WPF,我需要使用 EntityFramework 连接到 Postgre SQL 数据库。

我用谷歌搜索了一下,发现连接到 Postgre 的最流行方式是使用 npgsql 提供程序。

因此,我尝试从他们的网站安装 npgsql,然后发现 exe 安装程序仅安装适用于 .NET 4.0 和 4.5 的 npgsql。它还为 Visual Studio 安装了 vsix 扩展,它工作得很好。我必须下载 .NET 3.5 的 npgsql 库并手动添加对 Npgsql.dll 和 Npgsql.EntityFrameworkLegacy.dll 的引用。

我还将我的应用程序目标框架设置为 3.5,并使用 Nuget 安装 EntityFramework(4.1.10715 是与 .NET 3.5 一起使用的最新版本)。

然后我能够使用 edmx 向导连接到数据库(它检测到我的 Entityframework 设置为“3.5”)并生成了 edmx 和一些 类。

所以,问题是,当我尝试像这样在我的应用程序中获取一些数据时:

using (var db = new Entities())
{
    var list = db.MyItems.ToList()
}

它总是失败并出现错误:

The specified store provider cannot be found in the configuration, or is not valid.

我这样配置 App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="v11.0" />
        </parameters>
    </defaultConnectionFactory>
    <providers>
        <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
    </providers>
</entityFramework>
<startup>
    <supportedRuntime version="v2.0.50727" />
</startup>
<connectionStrings>
    <add name="myEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=Npgsql;provider connection string=&quot;PORT=5432;TIMEOUT=15;POOLING=True;MINPOOLSIZE=1;MAXPOOLSIZE=20;COMMANDTIMEOUT=20;COMPATIBLE=2.2.5.0;DATABASE=mydb;HOST=localhost;PASSWORD=postgres;USER ID=postgres&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

我想我应该在 App.config 中更改一些内容,但无法弄清楚哪里出了问题。

请帮忙。

缺少商店提供商。
商店提供商通常是 ADO.Net 提供商。通常在 machine.config 中注册,但在您的情况下可能不是。
当我部署应用程序时,我将它插入 App.Config 以避免修改 machine.config 但是你需要在输出目录中有提供者(所以一定要在编译期间复制它)。
反正我是在App.config中使用了这段配置(在配置中插入)

<system.data>
  <DbProviderFactories>
    <add name="Npgsql Data Provider" 
         invariant="Npgsql" 
         description=".Net Framework Data Provider for Postgresql Server" 
         type="Npgsql.NpgsqlFactory, Npgsql, Version=2.2.5.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"
         support="FF" />
  </DbProviderFactories>
</system.data>