简体   繁体   English

通过Entity框架插入当前数据库日期时间

[英]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. 我们有一个Web服务器,Web服务器上的时间可能会有所不同,因此我们需要在数据库服务器上使用datetime。

We have a database with a Not Null datetime column. 我们有一个带有Not Null datetime列的数据库。 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. 当我们使用不包含datetime列的SQL语句插入数据时,这很好。

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. 如果我们将datetime定义not null ,则将datetime设置为低日期,并将低日期插入数据库。
  • If we define the datetime as null , we get an exception on the insert that the value cannot be null. 如果我们将datetime定义为null ,我们在插入上得到一个异常,该值不能为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: 由于列具有数据库设置的默认值,因此您只需将datetime列标记为已计算:

[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 EntityTypeConfiguration类中,或

modelBuilder.Entity<MyClass>().Property(t => t.Date)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

in an OnModelCreating override. OnModelCreating覆盖中。

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. 这将导致EntityFramework在每次读取,插入或更新记录时读取列的值,但它永远不会设置它。

One way is to use UTC dateTime so in C# you can use 一种方法是使用UTC dateTime,所以在C#中你可以使用

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. 如果我们将datetime定义为null,我们在插入上得到一个异常,该值不能为null。

You should pass instead of null -> 你应该传递而不是null - >

DbNull.Value 

and then insert should pass. 然后插入应该通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM