jcvandan jcvandan - 1 year ago 166
C# Question

Unable to create database in PostreSQL using Npgsql and Entity Framework code first

I am attempting to set up my application to use Entity Framework with PostgreSQL, but I have run up against a problem. I have added

via nuget, and added the following provider factory to

<add name="Npgsql Data Provider"
description=".Net Framework Data Provider for Postgresql Server"
type="Npgsql.NpgsqlFactory, Npgsql,
Version=, Culture=neutral,
PublicKeyToken=5d8b90d52f46fda7" />

With the connection string:

<add name="MyDb" providerName="Npgsql"
connectionString="Server=localhost;Port=5432;Database=withoomph;User ID=postgres;Password=******;enlist=true" />

It seems to connect to the DB fine, but when I try and do any sort of action on the DB I get the following exception:

FATAL: 3D000: database "withoomph" does not exist

I am setting the database intitializer correctly when the db is set up like so:

static MyDB()
Database.SetInitializer<MyDB>(new CreateDatabaseIfNotExists<MyDB>());

So it should just simply create db when I try and do anything with my
right? I don't get it, been pulling my hair out all morning!

Answer Source

Unfortunately, Npgsql does not have (as of now) automatic schema creation code-first.

You can create your database first, and then connect to it.

Update (2016): Npgsql 3 now implements database creation code-first. Make sure you configure the correct connection factory to use NpgsqlConnections, either via code or via the XML settings, and use an appropriate Connection String.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download