Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the default Entity Framework and default date values

In my SQL Server database schema I have a data table with a date field that contains a default value of

CONVERT(VARCHAR(10), GETDATE(), 111)

which is ideal for automatically inserting the date into the new record when manually entering records in to the database.

The problem I have is that when using the Entity Framework and mapping the Date field, that the Entity Framework inserts a default value of DateTime.Min when the entity is instantiated.

I cannot map the Date field to a nullable DateTime, i.e. DateTime?, nor am I able to use either CONVERT or DateTime.Now.Today in the default value of the Entity Designer as it only accepts hard-coded constant values.

I can of course explicitly set the DateTime field in C# whenever the object is created, either explicitly in code, in the constructor of a partial class, or even during the saving changes event.

Are there any other ways of achieving what I want where the default value calculation stored in the database table is actually used instead?

like image 697
Justin Avatar asked Oct 22 '09 18:10

Justin


1 Answers

Just happened to cross through this issue. Entity Framework do not support default values on its own. You need to set the property StoreGeneratedPattern = Computed on the column in the Edmx file entity. The default value what you set in the Database will then precedence on what EF sets by default i.e. DateTime.Min

like image 157
user9038381 Avatar answered Sep 22 '22 22:09

user9038381