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 Npqsql
via nuget, and added
Not surprisingly, since your database withoomph
is not created yet, you should not able to use connection string where Database=withoomph;
is mentioned.
What you can do is to either create this database manually using createdb
or psql
, or change your connection string temporarily to use Database=postgres;
instead.
This should work because on all recent PostgreSQL versions database postgres
is guaranteed to exist after vanilla install and should be used just for this purpose - to get initial authenticated connection to create another database and issue CREATE DATABASE withoomph;
within your application.
However, after your new database is created, you should immediately disconnect from postgres
, connect to new withoomph
and continue normally.
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 NpgsqlConnection
s, either via code or via the XML settings, and use an appropriate Connection String.
In addition to mvp's answer, here's a code snippet I used to create the database. You need to run it before initializing EF. So, the trick is to switch the database name temporarily to 'postgres', which is guaranteed to exists after a vanilla install.
public void CreateDatabase(string connectionString)
{
var builder = new NpgsqlConnectionStringBuilder(connectionString);
var databaseName = builder.Database; // REMEMBER ORIGINAL DB NAME
builder.Database = "postgres"; // TEMPORARILY USE POSTGRES DATABASE
// Create connection to database server
using (var connection = new NpgsqlConnection(builder.ConnectionString))
{
connection.Open();
// Create database
var createCommand = connection.CreateCommand();
createCommand.CommandText = string.Format(@"CREATE DATABASE ""{0}"" ENCODING = 'UTF8'", databaseName);
createCommand.ExecuteNonQuery();
connection.Close();
}
}