Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute asp.net asp.net

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute


You cannot do this with an attribute because they are just meta information generated at compile time. Just add code to the constructor to initialize the date if required, create a trigger and handle missing values in the database, or implement the getter in a way that it returns DateTime.Now if the backing field is not initialized.

public DateTime DateCreated{   get   {      return this.dateCreated.HasValue         ? this.dateCreated.Value         : DateTime.Now;   }   set { this.dateCreated = value; }}private DateTime? dateCreated = null;


Add below to the DateTime property

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]


I have tested this on EF core 2.1

Here you cannot use either Conventions or Data Annotations. You must use the Fluent API.

class MyContext : DbContext{    public DbSet<Blog> Blogs { get; set; }    protected override void OnModelCreating(ModelBuilder modelBuilder)    {        modelBuilder.Entity<Blog>()            .Property(b => b.Created)            .HasDefaultValueSql("getdate()");    }}

Official doc