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)’.