一个DateTime属性的默认值设置为DateTime.Now的System.ComponentModel默认值Attrbute内
有没有人知道我怎么可以使用System.ComponentModel默认值属性的日期时间属性指定的默认值?
Does any one know how I can specify the Default value for a DateTime property using the System.ComponentModel DefaultValue Attribute?
例如我试试这个:
[DefaultValue(typeof(DateTime),DateTime.Now.ToString("yyyy-MM-dd"))]
public DateTime DateCreated { get; set; }
和预计的价值是恒定的前pression。
And it expects the value to be a constant expression.
这是与ASP.NET动态数据使用的范围内。我不想脚手架dateCreated会列,而只是提供DateTime.Now如果它不是present。我现在用的是实体框架为我的数据层
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
干杯,
安德鲁
您不能与属性做到这一点,因为他们是在编译时产生的只是元信息。只需添加code的构造,如果需要初始化日期,创建触发器,并在数据库中处理缺失值,或者实现吸气的方式,它返回DateTime.Now如果支持字段不被初始化。
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;