简体   繁体   English

C#ASP.NET MVC 4中的DateTime.Now

[英]DateTime.Now in Model C# ASP.NET MVC 4

I have created a model for Articles, and in the articles I am trying to implement a date created on initial create. 我为文章创建了一个模型,并且在文章中我试图实现在初始创建时创建的日期。

//Model //模型

    [Display(Name = "Date Created")]
    public DateTime dateCreated
    {
        get { return DateTime.Now; }
    }

It works well when I create an article, but it also sets the same date time value to all the other articles. 当我创建文章时,它工作得很好,但是它也为所有其他文章设置了相同的日期时间值。 :/ :/

Is there a way around this? 有没有解决的办法?

cheers. 干杯。

Putting that in a property will evaluate the DateTime.Now each time the property is accessed, so if you query it twice, you'll get two different values. 将其放在属性中将对DateTime.Now每次访问,因此,如果您两次查询,将获得两个不同的值。

There are a number of possible options for modeling this, but normally you'll want a read-only property set-ed in the constructor: 有许多可能的方法可以对此建模,但是通常您需要在构造函数中设置一个只读属性:

public Article()
{
    This.DateCreated = DateTime.Now;
}

[Display(Name = "Date Created")]
public DateTime DateCreated {get; private set;}

It works well when I create an article, but it also sets the same date time value to all the other articles. 当我创建文章时,它工作得很好,但是它也为所有其他文章设置了相同的日期时间值。

This is exactly why it is a bad idea. 这就是为什么这是一个坏主意的原因。 Get what you do is exposing the current date and time with that property. 得到的结果就是使用该属性公开当前日期和时间。

Why can't you set it right before you save your changes? 为什么在保存更改之前不能正确设置它?

For instance: 例如:

public override int SaveChanges()
{
  DateTime saveTime = DateTime.Now;
  foreach (var entry in this.ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Added))
   {
     if (entry.Property("dateCreated").CurrentValue == null)
       entry.Property("dateCreated").CurrentValue = saveTime;
    }
    return base.SaveChanges();

}

Here's what you need: 这是您需要的:

private DateTime? dateCreated;
public DateTime DateCreated
{
    get { return dateCreated ?? DateTime.Now; }
    set { dateCreated = value; }
}

What this does is wait until this property is first accessed. 这是等到第一次访问此属性。 Then, it will see if a created date has already been set and if not, it will set it to DateTime.Now . 然后,它将查看是否已设置创建日期,如果未设置,则将其设置为DateTime.Now For initial creates, this will usually happen when EF attempts to save it to the database, which is exactly when you want that to happen. 对于初始创建,通常会在EF尝试将其保存到数据库时发生,这正是您希望发生的时间。 It would only happen sooner if you tried to manually access the property before saving, but there's no good reason why you would do that. 如果您尝试在保存之前手动访问该属性,则只会更快地发生,但是没有充分的理由这么做。 The set method just allows a normal set, so when EF pulls this from the database, it will just set the private field and it will always be set to that. set方法只允许一个普通的设置,因此当EF从数据库中提取此设置时,它将仅设置私有字段,并且始终将其设置为该私有字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM