How to implement a DateTime entity property to set always DateTime.Now

30.2k views Asked by At

I've read a bunch about auto implemented properties but I still don't quite get it. I have and entity:

 public class News
    {
        public int NewsId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime Date { get; set; }
    }

Now I don't want the user to set date himself every time a new entity of News type is created. I want the record to be saved automatically with the datetime it's created. Thinking about it I suggest that it's enough to just modify the set for my property to something like :

public DateTime Date 
{
  get;
  set
  {
    Date = DateTime.Now;
  }
}

But reading about the topic I saw that the standard way is to create private variable and use it instead in the implementation. That's where I get a little bit lost.

private DateTime _date = null;
public DateTime Date
{ 

Well I'm not sure for the getter and setter implementations. It seems reasonable to have something like : set { _date = DateTime.Now;} and I have no idea how to deal with the get part since I want this data to be fetched from the database so something like : get {return _date;} doesn't make much sense to me even though almost every example with auto implementedset` returns the private variable. But I think that if the property is an entity this is not making a lot of sense.

3

There are 3 answers

4
Hans Kesting On BEST ANSWER

Some ways to return the current date:

 public DateTime Date { get { return DateTime.Now; } }

or

 public class News
 {
    public News()
    {
       Date = DateTime.Now;
    }
    public DateTime Date { get; private set; }
 }

The first one will always return the current date/time, even if that instance was created some time ago. The second one will return the date/time the instance was created. Both prevent the user from setting that Date value.

5
Christos On

You could add a constructor to your class and then initialize there your property.

public class News
{

   // properties goes here

   public News()
   {
       Date=DateTime.Now;
   }

}

A far better constructor would be the following

public News(int newsId, string title, string content)
{
    NewsId=newsId;
    Title=title;
    Content=content;
    Date=DateTime.Now;
}

That way you could create an object of type News in a single line of code.

News news = new News(1,"title1","whatever");
2
Youp Bernoulli On

Don't touch the getter and setter! They are auto generated from a template and will be overridden every once and a while. Instead, as you might have noticed the generated entities are declared partially, create a partial class and declare a constructor there that sets the _date or Date of you r entity to DateTime.Now on construction (just as you desired).

public partial class News
{
  public News()
  {
    this.Date = DateTime.Now;
  }
}