如何配置Entity Framework以允许数据库生成uuid用于PostgreSQL(npgsql)?

时间:2016-06-01 20:38:52

标签: asp.net postgresql asp.net-core entity-framework-core npgsql

我正在更新我们的dotnet核心项目,以便在后端而不是Microsoft SQL Server上使用PostgreSQL,并遇到两个使用GUID作为数据类型的表的情况。

错误

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Property CommentID on type is a database-generated uuid, which requires the PostgreSQL uuid-ossp extension. Add .HasPostgresExtension("uuid-ossp") to your context's OnModelCreating.

稍微谷歌后,我意识到我必须启用uuid扩展(不确定这是否可以自动化)然后成功生成pgAdmin中的uuid。

CREATE EXTENSION "uuid-ossp";
SELECT uuid_generate_v4();

不幸的是,我的dotnet项目仍然抱怨同样的错误。我在错误中看到它说添加.HasPostgresExtension(" uuid-ossp")到OnModelCreating 并且我已经在几个地方试过了但似乎无法找出应该添加的具体位置。

1 个答案:

答案 0 :(得分:6)

根据Shay的指令 - 更新到最新版本的Npgsql后,uuid扩展错误现在消失了。这是OnModelCreating在其他人尝试这一点时的样子片段:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.HasPostgresExtension("uuid-ossp");
    }