加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – EF 7为DateTime列设置初始默认值

发布时间:2020-12-15 18:34:10 所属栏目:百科 来源:网络整理
导读:我需要能够设置DateTime列的初始值. 当我指定“getutcdate()或DateTime.UtcNow时 entity.Property(e = e.ShipDate).DefaultValue("getutcdate()")entity.Property(e = e.ShipDate).DefaultValue(DateTime.UtcNow) 然后运行dnx. ef migration add InitialMigr
我需要能够设置DateTime列的初始值.

当我指定“getutcdate()或DateTime.UtcNow时

entity.Property(e => e.ShipDate).DefaultValue("getutcdate()")
entity.Property(e => e.ShipDate).DefaultValue(DateTime.UtcNow)

然后运行dnx. ef migration add InitialMigration EF使用以下命令生成迁移快照:

b.Property<DateTime?>("ShipDate")
  .Required()
  .Annotation("Relational:ColumnDefaultValue","getutcdate()")
  .Annotation("Relational:ColumnDefaultValueType","System.String");

当我使用DateTime.UtcNow …

b.Property<DateTime?>("ShipDate")
  .Annotation("Relational:ColumnDefaultValue","635754129448768827")
  .Annotation("Relational:ColumnDefaultValueType","System.DateTime");

和初始迁移:

ShipDate = table.Column(
  type: "datetime2",nullable: false,defaultValue: "getutcdate()"),

当我使用DateTime.UtcNow …

ShipDate = table.Column(
  type: "datetime2",nullable: true,defaultValue: new DateTime(2015,8,17,12,55,44,876,DateTimeKind.Unspecified)),

看起来它必须工作,但是当我将数据插入表中时,列的默认值是创建时间戳的“即时”.

我错过了什么吗?

另外,既然如此,如何在EF7中指定IDENTITY SEED?

谢谢

UPDATE
生成sql脚本后,我得到两个选项:

如果使用“getutcdate()”:

[ShipDate] datetime2 DEFAULT 'getutcdate()',

由于引号不起作用

或者如果使用DateTime.utcNow:

[ShipDate] datetime2 DEFAULT '2015-08-17 12:55:44.8760000'

这解释了我得到的静态价值.

我想我可以用这个来管理.
这是一个错误还是有正确的方法吗?
谢谢

解决方法

您想要设置默认值SQL,而不是常量值:
entity.Property(e => e.ShipDate).HasDefaultValueSql("getutcdate()");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读