Inserting current Database date time via Entity framework

十年热恋 提交于 2019-12-10 09:56:19

问题


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 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?


回答1:


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.




回答2:


One way is to use UTC dateTime so in C# you can use

DateTime.UtcNow

You could also set

DateTime dateTime = new DateTime();
dateTime = SqlDateTime.MinValue.Value;

You can even create extension method :

public static class DateExtension
    {
        public static DateTime SqlValidDateTime(this DateTime d)
        {
            return SqlDateTime.MinValue.Value;
        }
    }

Also for:

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

You should pass instead of null ->

DbNull.Value 

and then insert should pass.



来源:https://stackoverflow.com/questions/22225701/inserting-current-database-date-time-via-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!