1

I have a field in my model class like below:

[ScaffoldColumn(false)]
public DateTime DatePosted { get; set; }

I would like that this field be set to DateTime.Now by default, unless a value was given. In MSSQL server this can be achieved in the table design view by setting the date field's property "Default Value or Binding" to getdate() - I think, please correct me if I'm wrong.

Ronald
  • 1,532
  • 4
  • 18
  • 34

2 Answers2

2

you can set default values in constructor of your model class,

public YourModel(){
    this.DatePosted =DateTime.Now;
}
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
  • This will give he a date time with the date that the objects was created not the date that it was saved in the database – Gabriel Monteiro Nepomuceno Jun 10 '13 at 19:57
  • @GabrielMonteiroNepomuceno Then we can do it by overriding the SaveChanges method in the db context. In that method get the created objects and update their DatePosted. http://stackoverflow.com/questions/6156818/entity-framework-4-1-dbcontext-override-savechanges-to-audit-property-change – Jayantha Lal Sirisena Jun 11 '13 at 03:40
0

how can we add a DB contraint do do that.

some thing that will do the below SQL

[DateCreated] [datetime] NOT NULL DEFAULT GetDate(),

Ahmed
  • 1,985
  • 1
  • 13
  • 8