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

后端 未结 21 1426
终归单人心
终归单人心 2020-11-29 22:53

Does any one know how I can specify the Default value for a DateTime property using the System.ComponentModel DefaultValue Attribute?

for example I try this:

21条回答
  •  悲&欢浪女
    2020-11-29 23:10

    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;
    

提交回复
热议问题