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

6
我正在将我们的dotnet core项目更新为在后端使用PostgreSQL而不是Microsoft SQL Server,并遇到了两个表使用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项目仍然出现相同的错误。 我在错误信息中看到它说要在OnModelCreating中添加.HasPostgresExtension("uuid-ossp"),我已经尝试了几个位置,但似乎无法确定应该在哪里添加。


1
HasPostgresExtension()需要放置在你的上下文(context)的OnModelCreating中,就像错误所说的那样。如果没有,请发布您上下文的相关部分。请注意,您必须使用来自Npgsql不稳定源的至少1.0.0-rc3-ci-39版本才能使其正常工作。 - Shay Rojansky
1个回答

12

根据Shay的指示-在更新到最新版本的Npgsql之后,uuid扩展错误已经消失。以下是一个代码片段,供其他人尝试使用:


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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接