EF连接PostgreSql

1.用nuget安装npgsql和EF

注意,Nuget一定要安装Npgsql的2.2.7版本,更高版本nuget在后面安装EF的时候无法自动解析。

install-Package Npgsql -Version 2.2.7

install-package Npgsql.EntityFramework

 

2.给app.config增加DbProviderFactories

注意红字部分,nuget不会自动增加,需要手工增加,否则会报异常:

The ADO.NET provider with invariant name 'Npgsql' is either not registered in the machine or application config file, or could not be loaded

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.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="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
</providers>


</entityFramework>

<system.data>
<DbProviderFactories>
<add name="Npgsql Data Provider" invariant="Npgsql" description="Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>

<connectionStrings>
<add name ="PostgreSqlDb" connectionString ="server=127.0.0.1;User Id=user;password=pwd;database=dbname" providerName="Npgsql"/>
</connectionStrings>
</configuration>

 

3.坑

如果程序跑起来报以下错误,在确定安装了正确版本的PostgreSqlDb Data Provider之后,请检查.net framework的版本是否正确。比如没安装.net framework 4.5。

Method not found: 'System.Data.Common.DbProviderFactory System.Data.Common.DbProviderFactories.GetFactory(System.Data.Common.DbConnection)'.

posted @   深圳大漠  阅读(4599)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示