I want to apply a timestamp to my Entity Framework project. I have a class listed below. I hoped that this class would grab the current DateTime. But instead it provides me a field to enter my datetime. I want this to grab the current datetime.
public class Answer
{
public int ID { get; set; }
public string Answers {get; set;}
public System.DateTime DateCreated { get; set; }
public string Division { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
}
Below is the line of code that i know is wrong.
public System.DateTime DateCreated { get; set; }
i am a little unsure of how to go about this. I am new to entity and new to MVC. Any help would be greatly appreciated.
You could initialize it in the constructor e.g.
However, I get the impression that your
Answerclass isn’t actually an entity but a view model. For actual entities, what I tend to do with fixed/generated values like this is let the database populate the field with a default value e.g.GetUtcDate()and then in the EF designer set theStoreGeneratedPatternproperty toComputed– that way when you pull down your entities theCreatedDatewill be pre-populated. This gives you data integrity both ways as you won’t be able to overwrite the field in the database either when pushing your data back up.Then it’s just a case of mapping your
Answerentity to yourAnswerview model therefore nothing has to be initialized.