在 System.ComponentModel 默认值属性中将 DateTime 属性的默认值设置为 DateTime.Now
有人知道如何使用 System.ComponentModel DefaultValue 属性为 DateTime 属性指定默认值吗?
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; }
它期望值是一个常量表达式.
And it expects the value to be a constant expression.
这是在与 ASP.NET 动态数据一起使用的上下文中.我不想搭建 DateCreated 列的脚手架,而是简单地提供 DateTime.Now 如果它不存在.我使用实体框架作为我的数据层
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
干杯,
安德鲁
你不能用属性来做到这一点,因为它们只是在编译时生成的元信息.如果需要,只需向构造函数添加代码以初始化日期,创建触发器并处理数据库中的缺失值,或者以返回 DateTime.Now 的方式实现 getter(如果支持字段未初始化).
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;