views:

3057

answers:

4

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:

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

And it expects the value to be a constant expression.

This is in the context of using with ASP.NET Dynamic Data. I do not want to scaffold the DateCreated column but simply supply the DateTime.Now if it is not present. I am using the Entity Framework as my Data Layer

Cheers,

Andrew

+3  A: 

You cannot do this with an attribute because they are just meta information generated at compile time. Just at code to the constructor the initialize the date if required, create an 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 == default(DateTime))
         ? DateTime.Now
         : this.dateCreated;
   }

   set { this.dateCreated = value; }
}
private DateTime dateCreated = default(DateTime);
Daniel Brückner
Thank you, before you edit I went the other way and intercepted the setter. Cheers for the help :-)
REA_ANDREW
Now I have implemented your example thanks for your time
REA_ANDREW
+1  A: 

How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?

In L2S you can add

public partial class NWDataContext { partial void InsertCategory(Category instance) { if(Instance.Date == null) Instance.Data = DateTime.Now;

    ExecuteDynamicInsert(instance);
}

}

EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.

Wizzard
A: 
public DateTime DateCreated
{
   get
   {
      return (this.dateCreated == default(DateTime))
         ? this.dateCreated = DateTime.Now
         : this.dateCreated;
   }

   set { this.dateCreated = value; }
}
private DateTime dateCreated = default(DateTime);
bobac
A: 

Hi there,

I also wanted this and came up with this solution (I'm only using the date part - a default time makes no sense as a PropertyGrid default):

public class DefaultDateAttribute : DefaultValueAttribute {
  public DefaultDateAttribute(short yearoffset)
    : base(DateTime.Now.AddYears(yearoffset).Date) {
  }
}

This just creates a new attribute that you can add to your DateTime property. E.g. if it defaults to DateTime.Now.Date:

[DefaultDate(0)]
Michel Smits