通过实体框架插入当前数据库日期时间 [英] Inserting current Database date time via Entity framework
问题描述
我们希望将当前日期时间放入数据库列中。
We want to put the current datetime into a database column.
我们有一个Web场,Web服务器上的时间可以变化,因此我们需要使用数据库服务器上的日期时间。
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.
我们有一个数据库,其中的日期时间列为 Not Null
。此列具有当前时间的默认日期时间。
We have a database with a Not Null
datetime column. This column has a default datetime of current time.
当我们使用不包含datetime列的SQL语句插入数据时,此方法很好用。
This works fine when we insert data using a SQL statement that does not include the datetime column.
从实体框架:
- 如果我们将日期时间定义为
不为空
,则将datetime设置为低日期,并将低日期插入数据库中。 - 如果将日期时间定义为
null
,我们在插入项上得到了一个例外,该值不能为null。
- 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.
我们可以使用数据库来解决此问题如果插入值为低日期,则触发器将datetime更改为当前datetime。
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?
推荐答案
数据库设置了默认值,您可以简单地将datetime列标记为已计算:
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; }
或流利的地图绘制
this.Property(t => t.Date)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
或
modelBuilder.Entity<MyClass>().Property(t => t.Date)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
在 OnModelCreating
替代项中。
这将导致EntityFramework在每次读取,插入或更新记录时读取该列的值,但永远不会对其进行设置。
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.
这篇关于通过实体框架插入当前数据库日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!