C# 在 System.ComponentModel 默认值属性中将 DateTime 属性的默认值设置为 DateTime.Now

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/691035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:38:54  来源:igfitidea点击:

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

c#asp.netentity-frameworkasp.net-core-2.1ef-core-2.1

提问by REA_ANDREW

Does any one know how I can specify the Default value for a DateTime property using the System.ComponentModel DefaultValue Attribute?

有谁知道如何使用 System.ComponentModel DefaultValue 属性为 DateTime 属性指定默认值?

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

这是在与 ASP.NET 动态数据一起使用的上下文中。我不想搭建 DateCreated 列的脚手架,而是简单地提供 DateTime.Now(如果它不存在)。我使用实体框架作为我的数据层

Cheers,

干杯,

Andrew

安德鲁

采纳答案by Daniel Brückner

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.

您不能使用属性执行此操作,因为它们只是在编译时生成的元信息。如果需要,只需将代码添加到构造函数以初始化日期,创建触发器并处理数据库中的缺失值,或者以返回 DateTime.Now 的方式实现 getter(如果支持字段未初始化)。

public DateTime DateCreated
{
   get
   {
      return this.dateCreated.HasValue
         ? this.dateCreated.Value
         : DateTime.Now;
   }

   set { this.dateCreated = value; }
}

private DateTime? dateCreated = null;

回答by Wizzard

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

您目前如何处理这取决于您使用的是 Linq to SQL 还是 EntityFramework 的模型?

In L2S you can add

在 L2S 中,您可以添加

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.aspxfor more info on EF buisiness logic.

EF 有点复杂,请参阅http://msdn.microsoft.com/en-us/library/cc716714.aspx,了解有关 EF 业务逻辑的更多信息。

回答by bobac

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

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

回答by Michel Smits

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):

我也想要这个并提出了这个解决方案(我只使用日期部分 - 默认时间作为 PropertyGrid 默认值没有意义):

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:

这只会创建一个新属性,您可以将其添加到 DateTime 属性中。例如,如果它默认为 DateTime.Now.Date:

[DefaultDate(0)]

回答by Terence Golla

A simple solution if you are using the Entity Framework is the add a partical class and define a constructor for the entity as the framework does not define one. For example if you have an entity named Example you would put the following code in a seperate file.

如果您使用实体框架,一个简单的解决方案是添加一个部分类并为实体定义一个构造函数,因为框架没有定义一个构造函数。例如,如果您有一个名为 Example 的实体,您可以将以下代码放在一个单独的文件中。

namespace EntityExample
{
    public partial class Example : EntityObject
    {
        public Example()
        {
            // Initialize certain default values here.
            this._DateCreated = DateTime.Now;
        }
    }
}

回答by Nuri

I needed a UTC Timestamp as a default value and so modified Daniel's solution like this:

我需要一个 UTC 时间戳作为默认值,因此修改了 Daniel 的解决方案,如下所示:

    [Column(TypeName = "datetime2")]
    [XmlAttribute]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
    [Display(Name = "Date Modified")]
    [DateRange(Min = "1900-01-01", Max = "2999-12-31")]
    public DateTime DateModified {
        get { return dateModified; }
        set { dateModified = value; } 
    }
    private DateTime dateModified = DateTime.Now.ToUniversalTime();

For DateRangeAttribute tutorial, see this awesome blog post

对于 DateRangeAttribute 教程,请参阅这篇很棒的博客文章

回答by Erhhung

Creating a new attribute class is a good suggestion. In my case, I wanted to specify 'default(DateTime)' or 'DateTime.MinValue' so that the Newtonsoft.Json serializer would ignore DateTime members without real values.

创建一个新的属性类是一个很好的建议。就我而言,我想指定 'default(DateTime)' 或 'DateTime.MinValue' 以便 Newtonsoft.Json 序列化程序将忽略没有实际值的 DateTime 成员。

[JsonProperty( DefaultValueHandling = DefaultValueHandling.Ignore )]
[DefaultDateTime]
public DateTime EndTime;

public class DefaultDateTimeAttribute : DefaultValueAttribute
{
    public DefaultDateTimeAttribute()
        : base( default( DateTime ) ) { }

    public DefaultDateTimeAttribute( string dateTime )
        : base( DateTime.Parse( dateTime ) ) { }
}

Without the DefaultValue attribute, the JSON serializer would output "1/1/0001 12:00:00 AM" even though the DefaultValueHandling.Ignore option was set.

如果没有 DefaultValue 属性,即使设置了 DefaultValueHandling.Ignore 选项,JSON 序列化程序也会输出“1/1/0001 12:00:00 AM”。

回答by DSW

It is possible and quite simple:

这是可能的,而且很简单:

for DateTime.MinValue

为了 DateTime.MinValue

[System.ComponentModel.DefaultValue(typeof(DateTime), "")]

for any other value as last argument of DefaultValueAttributespecify string that represent desired DateTime value.

对于任何其他值作为DefaultValueAttribute表示所需 DateTime 值的指定字符串的最后一个参数。

This value must be constant expression and is required to create object (DateTime) using TypeConverter.

该值必须是常量表达式,并且需要DateTime使用TypeConverter.

回答by Robertas

I think the easiest solution is to set

我认为最简单的解决方案是设置

Created DATETIME2 NOT NULL DEFAULT GETDATE()

in column declaration and in VS2010 EntityModel designer set corresponding column property StoreGeneratedPattern = Computed.

在列声明和 VS2010 EntityModel 设计器中设置相应的列属性StoreGeneratedPattern = Computed

回答by Muhammad Soliman

Simply consider setting its value in the constructor of your entity class

只需考虑在实体类的构造函数中设置其值

public class Foo
{
       public DateTime DateCreated { get; set; }
       public Foo()
       {
           DateCreated = DateTime.Now;
       }

}