Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework and Default Date

I have a table in SQL, within that table I have DateTime column with a default value of GetDate()

In entity framework I would like it to use the SQL date time instead of using the local date time of the computer the console app is running on (the SQL server is 1 hour behind).

The column does not allow nulls either, currently it passes in a date value of 1/1/0001 and I get an error:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated.

Thank you!

like image 414
TheWebGuy Avatar asked Feb 06 '13 12:02

TheWebGuy


3 Answers

  1. Open edmx designer
  2. Select your DateTime column
  3. Go to properties and change StoreGeneratedPattern from None to Computed

That will tell EF not to insert value for that column, thus column will get default value generated by database. Keep in mind that you will not be able to pass some value.

like image 63
Sergey Berezovskiy Avatar answered Nov 07 '22 15:11

Sergey Berezovskiy


If you're using Fluent API, just add this to your DbContext class:

        modelBuilder.Entity<EntityName>()
            .Property(p => p.PropertyName)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
like image 38
John M Avatar answered Nov 07 '22 15:11

John M


Set columnType for that entity in OnModelCreating Method: modelBuilder.Entity().Property(s => s.ColumnName).HasColumnType("datetime2");

like image 44
user2065203 Avatar answered Nov 07 '22 15:11

user2065203