EF連線PostgreSql

szjay發表於2016-01-15

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

相關文章