2

I'm using .NET 7 with Entity Framework Core and postgresql (npgsql).

I want to add autogenerated CreateOn and ModifiedOn columns to all my tables. I want them to update to the current datetime when a row is inserted or updated respectively.

So my models all inherit an abstract class with that has two, data annotated, columns.

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTimeOffset CreatedDate { get; set; }

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTimeOffset UpdatedDate { get; set; }

I assumed, like it says in the .NET docs, this would autogenerate datetime when a row is inserted and updated. However, this autogeneration isn't shown in the migration, and when seeding the database I get an error

null is not an acceptable value for createdDate

(which I leave blank when seeding because it's supposed to be autogenerated). To me this means that autogeneration isn't working.

Online resources tell me to add the following line to the DbContext OnModelCreate function to autogenerate:

modelBuilder.Entity<EamEntity>()
            .Property(e => e.CreatedDate)
            .HasDefaultValueSql("NOW()");

modelBuilder.Entity<EamEntity>()
            .Property(e => e.UpdatedDate)
            .HasDefaultValueSql("NOW()");

This seems to work (I've only tried inserting), however, this isn't a feasible because I have many tables that each have these datetime columns, meaning I'd have to do this for each column.

This makes me think that I'm missing something. Is there a solution that just makes data annotations work?? Thank you!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

While you can define a default value for insertion (as you've done above), the same doesn't work for updating; see the documentation for more details.

To apply configuration to many properties in bulk, see model bulk configuration in the EF documentation.

Shay Rojansky
  • 15,357
  • 2
  • 40
  • 69