首先无法使用Npgsql和Entity Framework代码在PostreSQL中创建数据库
我正在尝试将我的应用程序设置为与PostgreSQL一起使用Entity Framework,但是遇到了一个问题。我已经通过nuget添加了 Npqsql
,并将以下提供程序工厂添加到了 web.config
:
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 the following provider factory to web.config
:
<system.data>
<DbProviderFactories>
<add name="Npgsql Data Provider"
invariant="Npgsql"
description=".Net Framework Data Provider for Postgresql Server"
type="Npgsql.NpgsqlFactory, Npgsql,
Version=2.0.12.0, Culture=neutral,
PublicKeyToken=5d8b90d52f46fda7" />
</DbProviderFactories>
</system.data>
使用连接字符串:
<add name="MyDb" providerName="Npgsql"
connectionString="Server=localhost;Port=5432;Database=withoomph;User ID=postgres;Password=******;enlist=true" />
似乎可以连接到数据库,但是当我尝试对数据库进行任何操作时DB,我得到以下异常:
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:数据库 withoomph不存在
按如下所示设置数据库时,我正在正确设置数据库初始化器:
I am setting the database intitializer correctly when the db is set up like so:
static MyDB()
{
Database.SetInitializer<MyDB>(new CreateDatabaseIfNotExists<MyDB>());
}
因此,当我尝试对 DbContext 对吗?我不明白,整个上午都在梳头!
So it should just simply create db when I try and do anything with my DbContext
right? I don't get it, been pulling my hair out all morning!
不幸的是,Npgsql还没有(到目前为止) )自动模式创建代码优先。
Unfortunately, Npgsql does not have (as of now) automatic schema creation code-first.
您可以先创建数据库,然后再连接数据库。
You can create your database first, and then connect to it.
更新(2016):Npgsql 3现在首先实现数据库创建代码。确保通过代码或XML设置将正确的连接工厂配置为使用 NpgsqlConnection
,并使用适当的连接字符串。
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.