请问怎么给属性添加sql默认值GETDATE()

来源:3-6 【应用】创建数据库

hllive

2020-07-15

请问用Attribute怎么给createTime属性添加MSSQL数据库的默认值GETDATE()

public DateTime createTime { get; set; }
写回答

1回答

阿莱克斯刘

2020-07-16

我找了ef的官方文档,似乎并没有给datetime设置默认值的attribute,在网上找到别人关于设置datetime默认值的提问,原帖地址: https://stackoverflow.com/questions/691035/setting-the-default-value-of-a-datetime-property-to-datetime-now-inside-the-syst

//img1.sycdn.imooc.com/szimg/5f0f32a90860a45f18570940.jpg

给出的回答是:DateTime 没有相对应的默认attribute,因为使用attribute得到的的默认值是编译时候产生的meta数据(是固定值),然而我们设置默认的时间需要runtime的数据(是动态的)。

所以结局方案有两个,

1)使用GETDATE(),你已经知道了。

2)重写CreateTime的setter和getter:

public DateTime DateCreated{
   get
   {
      return this.dateCreated.HasValue
         ? this.dateCreated.Value
         : DateTime.Now;
   }
   set { this.dateCreated = value; }
}

private DateTime? dateCreated = null;


0
0

.Net 开发电商后端API 从0到精通RESTful

. Net 实战+RESTful思想纵深课程,开发优雅RESTful风格API。

979 学习 · 553 问题

查看课程