7

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!

TheWebGuy
  • 11,429
  • 16
  • 52
  • 72
  • 1
    can you please share your codes? – spajce Feb 06 '13 at 12:38
  • You must avoid that EF sends the date to the database at all to avoid that the GetDate() value in the DB gets overridden. Search for `DatabaseGenerated` or `StoreGeneratedPattern` (it depends on EF version you are using) and `Computed` to find an indication into the right direction. – Slauma Feb 06 '13 at 18:34

3 Answers3

22
  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.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • 3
    Why EF doesn't provide this functionality by default? In Database-First scenarios It is very hard to maintain when re-creating the model. – T.Y. Kucuk Mar 03 '16 at 09:19
3

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

        modelBuilder.Entity<EntityName>()
            .Property(p => p.PropertyName)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
John M
  • 2,510
  • 6
  • 23
  • 31
1

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