Tuesday, December 17, 2013

Npgsql with Entity Framework 6

I spent some time to find the way, how to use Npgsql with Entity Framwork 6. Here is what I have found. This solution is tested with Npgsql version commited on 13.12.2013.

Assemblies

Entity Framerok install from Nuget repository, Npgsql clone git repository (https://github.com/franciscojunior/Npgsql2.git) and compile as fot .NET 4.5, reference it in your project with assemby Npgsql.EntityFramework.

Configuration

Add these lines to your Web.config

<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>
  <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>

Create (and configure) your Dbcontext

public MyDbContext()
    : base("ConnectionStringName")
{
    Database.SetInitializer<MyDbContext>(null);
}

public DbSet<User> Users { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    modelBuilder.HasDefaultSchema("public");

    // user
    var user = modelBuilder.Entity<User>();
    user.ToTable("user")
        .HasKey(t => t.Id)
        .Property(t => t.Id)
            .HasColumnName("id");

    base.OnModelCreating(modelBuilder);
}


Line Database.SetInitializer<MyDbContext>(null); is avoiding all model startup exceptions like:

ERROR: 42P01: relation "dbo.__MigrationHistory" does not exist
ERROR: schema "dbo" does not exist

Because Npgsql doesn't support schema creation, you must create database manually and you can use this line to skip schema migrations and creation/updates.

2 comments:

  1. Although it's not possible to use HasDefaultSchema with EF4, most of the code still applies.

    Thanks!

    ReplyDelete