Shiraz Bhaiji Shiraz Bhaiji - 7 months ago 108
SQL Question

Inserting current Database date time via Entity framework

We want to put the current datetime into a database column.

We have a web farm where the time on the web servers can vary, we therefore need to use the datetime on the database server.

We have a database with a

Not Null
datetime column. This column has a default datetime of current time.

This works fine when we insert data using a SQL statement that does not include the datetime column.

From Entity Framework:

  • If we define the datetime as
    not null
    , the datetime is set to low date, and low date is inserted into the database.

  • If we define the datetime as
    , we get an exception on the insert that the value cannot be null.

We could fix this using a database trigger that changed the datetime to current datetime if the insert value is low date.

Does anyone have a better solution?


As the column has a default value set by the database you can simply mark the datetime column as computed:

property DateTime Date { get; set; }

or in fluent mapping

this.Property(t => t.Date)

in a EntityTypeConfiguration class, or

modelBuilder.Entity<MyClass>().Property(t => t.Date)

in an OnModelCreating override.

This will cause EntityFramework to read the value of the column at each read, insert or update of a record, but it will never set it.