0

I have a code that automatically completes creation time and last updated time. When creating an entry the dates are inserted in both places, but when updating the code does not update LastUpdatedDate. The code is taken from the following website: docs.microsoft

public class ReservationModel
{
    public int Id { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? CreatedDate = DateTime.Now;

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? LastUpdateDate = DateTime.Now;
}

DB:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ReservationModel>()
      .Property(b => b.CreatedDate)
      .HasDefaultValueSql("getdate()");

    modelBuilder.Entity<ReservationModel>()
        .Property(b => b.LastUpdateDate)
         .ValueGeneratedOnAddOrUpdate()
         .HasDefaultValueSql("getdate()");
}

Why is that and how to fix it?

MarcinAWK
  • 63
  • 1
  • 11
  • ValueGeneratedOnAddOrUpdate tells EF "the database generates this; don't bother with it yourself because anything you do will be overwritten". Put a trigger on the DB to update it – Caius Jard Mar 19 '22 at 10:49
  • how to put this trigger? – MarcinAWK Mar 22 '22 at 10:48
  • You didn't say your DB, but it's not hard to google for e.g. "updateddate trigger sqlserver" -> https://stackoverflow.com/questions/7737945/how-to-create-trigger-for-auto-update-modified-date-with-sql-server-2008 – Caius Jard Mar 22 '22 at 10:56

0 Answers0