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

chr*_*ris 6 asp.net postgresql npgsql entity-framework-core asp.net-core

我正在更新我们的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.
Run Code Online (Sandbox Code Playgroud)

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

CREATE EXTENSION "uuid-ossp";
SELECT uuid_generate_v4();
Run Code Online (Sandbox Code Playgroud)

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

chr*_*ris 7

根据Shay的指令 - 更新到最新版本的Npgsql后,uuid扩展错误现在消失了.以下是OnModelCreating在其他人尝试此操作时的样子片段:

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

        builder.HasPostgresExtension("uuid-ossp");
    }
Run Code Online (Sandbox Code Playgroud)