Postgresql and Entity Framework

N.J picture N.J · Apr 1, 2016 · Viewed 13.2k times · Source

In my project I am trying to use Entity Framework along with PostgreSql. But I am not able to connect to my database. I am not getting any error, it just gets stuck. I think something is wrong with my app.config, but I am not able to find out what.

App.config:

<?xml version="1.0" encoding="utf-8"?>
<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>
    <entityFramework>
        <defaultConnectionFactory type="Npgsql.NpgsqlFactory, Npgsql" />
        <providers>
            <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="Entities" 
             connectionString="server=localhost;user id=postgres;password=4321;database=postgis" 
             providerName="Npgsql" />
    </connectionStrings>
</configuration>

DbContext:

public class Entities : DbContext
{
    public Entities() : base("Entities")
    {
    }

    //rest of the code
}

mycode.cs

using (var db = new Entities()) // when debug it stuck here and keep running 
{
 // some test code
}

EDIT:

I get the following error :
"The Entity Framework provider type 'Npgsql.NpgsqlServices, Npgsql.EntityFramework' registered in the application config file for the ADO.NET provider with invariant name 'Npgsql' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application.

Answer

Panagiotis Kanavos picture Panagiotis Kanavos · Apr 1, 2016

The problem points to a wrong provider type or assembly name.

<entityFramework>
    <defaultConnectionFactory type="Npgsql.NpgsqlFactory, Npgsql" />
    <providers>
        <provider invariantName="Npgsql" 
                  type="Npgsql.NpgsqlServices, Npgsql.EntityFramework"  />
    </providers>
</entityFramework>

The assembly name is wrong. The assembly installed by the EntityFramework6.Npgsql package is EntityFramework6.Npgsql.dll. In fact, adding the package to a new project sets the correct provider line:

<providers>
  <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>