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

c# datetime entity-framework properties

Question

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.

1
3
11/28/2013 8:43:08 AM

Accepted 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
11/28/2013 8:49:58 AM

Popular Answer

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");


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow