如何告诉实体框架允许SQL Server为字段提供定义的默认值? [英] How do I tell Entity Framework to allow SQL Server to provide a defined default value for a field?

查看:166
本文介绍了如何告诉实体框架允许SQL Server为字段提供定义的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I used the following SQL script to enable setting current time in a field, when a new row is added to a table:

我使用以下SQL脚本来启用设置当前时间的一个字段c> ALTER TABLE [项目] ADD CONSTRAINT DF_Items DEFAULT GETDATE()FOR [CreationDate]

ALTER TABLE [Items] ADD CONSTRAINT DF_Items DEFAULT GETDATE() FOR [CreationDate]

现在我使用实体框架来处理此表,并向其添加新行。我想要做的是允许特定列从SQL Server本身接收其值,而不必自己提供该值。
在Visual Basic中将特定列的值设置为 Nothing 将使用 DateTime.MinValue 填充该字段,这是不是我想要的(而且SQL Server不支持,顺便说一下)。

Now I am using Entity Framework to work with this table, and add new rows to it. What I want to do is allow that specific column to receive its value from SQL Server itself, and not have to provide the value myself. Setting that specific column's value to Nothing in Visual Basic fills the field with DateTime.MinValue, which is not what I want (and SQL Server doesn't support, by the way).

为了使这项工作有什么变化?

What changes do I have to make to make this work?

推荐答案

您必须在EDMX设计器中设置 StoreGeneratedPattern (或 DatabaseGeneratedOption 在代码中)到身份为该日期属性。 EF始终为未存储生成的未填充属性发送.NET默认值。将模式设置为 Identity 会告诉EF在插入期间该值是在DB中生成的,它将重新调用其值。如果您将模式从默认值更改,您将无法在应用程序中设置属性。

You must set StoreGeneratedPattern in EDMX designer (or DatabaseGeneratedOption in code first) to Identity for that date property. EF always sends .NET default value for not filled property which is not store generated. Setting the pattern to Identity will tell EF that value is generated in DB during insert and it will requery its value. If you change the pattern from default value you will not be able to set the property in your application.

这篇关于如何告诉实体框架允许SQL Server为字段提供定义的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆