一个DateTime属性的默认值设置为DateTime.Now的System.ComponentModel默认值Attrbute内 [英] Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

查看:1183
本文介绍了一个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;

这篇关于一个DateTime属性的默认值设置为DateTime.Now的System.ComponentModel默认值Attrbute内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆