How to create CreatedOn and UpdatedOn using EF Cor

2019-07-13 02:22发布

问题:

In Code First approach, how to define my entity so that:

  • CreatedOn NOT NULL - value is generated on insert by the db with the current timestamp
  • Updated NULL - value is generated on update by the db with the current timestamp

Sample Entity:

public class MyEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column(TypeName = "TIMESTAMP")]
    public DateTime CreatedOn { get; set; }
    [Column(TypeName = "TIMESTAMP")]
    public DateTime UpdatedOn { get; set; }
}

DbContext:

public class MyContext : DbContext
{
    public MyContext(DbContextOptions options) : base(options) {}

    public DbSet<MyEntity> Entities { get; set; }
}

End result in the database should be:

  • CreatedOn NOT NULL - Has no Extra - Default could be CURRENT_TIMESTAMP
  • UpdatedOn NULL - Extra on update CURRENT_TIMESTAMP - No Default or Default is NULL