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:
not null, the datetime is set to low date, and low date is inserted into the database.null, 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:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
property DateTime Date { get; set; }
or in fluent mapping
this.Property(t => t.Date)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
in a EntityTypeConfiguration class, or
modelBuilder.Entity<MyClass>().Property(t => t.Date)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With