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

查看:36
本文介绍了在 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;

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

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