简体   繁体   中英

Computed timestamps in EF Core entity backed by Postgres

I'm using EF Core v5 and the Npgsql EF Core provider v5 for Postgres v14.

I want CreatedAt and UpdatedAt computed columns to be set automatically. They are both of type DateTime .

I tried 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);

But that throws when creating the table ( Npgsql.PostgresException (0x80004005): 42601: syntax error at or near ")" ).

If I remove the code above then everything works, so the problem is isolated to that code.

I think timestamp with time zone is correct for UTC timestamps , but the overall syntax is obviously wrong. How do I fix it?

timestamp with time zone is a Postgresql type name rather than a value. The value of the current timestamp with time zone is current_timestamp or now() . Try

.HasDefaultValueSql("now()");

用这个:

.HasDefaultValueSql("CURRENT_TIMESTAMP");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM