请问怎么给属性添加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
给出的回答是: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;
00
相似问题