Home > Software engineering >  Computed timestamps in EF Core entity backed by Postgres
Computed timestamps in EF Core entity backed by Postgres

Time:11-09

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?

CodePudding user response:

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

CodePudding user response:

Use this:

.HasDefaultValueSql("CURRENT_TIMESTAMP");
  • Related