Setting a DateTime Property's default value to DateTime. Now you're in the System. Default Value Attribute for ComponentModel

asp.net asp.net-core-2.1 c# ef-core-2.1 entity-framework

Question

Does anybody know how I may use the System.ComponentModel DefaultValue Attribute to set the default value for a DateTime property?

I'll give you an example:

[DefaultValue(typeof(DateTime),DateTime.Now.ToString("yyyy-MM-dd"))]
public DateTime DateCreated { get; set; }

Additionally, it anticipates a constant expression for the value.

This refers to the use of ASP.NET Dynamic Data. I only want to input the DateTime instead of scaffolding the DateCreated column. If it is not already there. My data layer is called Entity Framework.

Cheers,

Andrew

1
88
9/22/2018 9:55:55 AM

Accepted Answer

Due to the fact that attributes are only meta data produced at compile time, you cannot accomplish anything with them. Simply add code to the constructor to initialize the date if necessary, implement the getter so that it returns DateTime, or build a trigger to handle missing values in the database. Suppose the backing field hasn't been initialized yet.

public DateTime DateCreated
{
   get
   {
      return this.dateCreated.HasValue
         ? this.dateCreated.Value
         : DateTime.Now;
   }

   set { this.dateCreated = value; }
}

private DateTime? dateCreated = null;
91
1/22/2013 3:06:30 PM

Popular Answer

To the DateTime property, add the following.

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow