Ronald
Ronald

Reputation: 1542

EF Code First date field to equal current time

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.

Upvotes: 1

Views: 610

Answers (2)

Ahmed
Ahmed

Reputation: 2157

how can we add a DB contraint do do that.

some thing that will do the below SQL

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

Upvotes: 0

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

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

public YourModel(){
    this.DatePosted =DateTime.Now;
}

Upvotes: 2

Related Questions