由 Postgres 支持的 EF Core 实体中的计算时间戳

Computed timestamps in EF Core entity backed by Postgres

我正在为 Postgres v14 使用 EF Core v5 和 Npgsql EF Core 提供程序 v5。

我希望自动设置 CreatedAtUpdatedAt 计算列。它们都是 DateTime.

类型

我试过了this:

builder
  .Property(x => x.CreatedAt)
  .IsRequired()
  .HasDefaultValueSql("timestamp with time zone");

builder
  .Property(x => x.UpdatedAt)
  .IsRequired()
  .HasComputedColumnSql("timestamp with time zone", stored: true);

但是在创建 table (Npgsql.PostgresException (0x80004005): 42601: syntax error at or near ")") 时抛出错误。

如果我删除上面的代码,那么一切正常,所以问题与该代码无关。

我认为timestamp with time zone对于UTC timestamps是正确的,但整体语法显然是错误的。我该如何解决?

timestamp with time zone 是 Postgresql 类型名称而不是值。当前带时区的时间戳的值为current_timestampnow()。尝试

.HasDefaultValueSql("now()");

使用这个:

.HasDefaultValueSql("CURRENT_TIMESTAMP");