Search code examples
c#postgresqlentity-frameworkentity-framework-corenpgsql

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?


Solution

  • 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()");