EntityFramework不使用默认值更新列 [英] EntityFramework not updating column with default value

查看:50
本文介绍了EntityFramework不使用默认值更新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过EntityFramework 4(EF)将对象插入SQL Server数据库中.在接收表上有一列( CreatedDate ),其默认值设置为 getdate().因此,我没有将其提供给EF,前提是SQL Server将其默认值设置为 getdate().

I am inserting an object into a SQL Server db via the EntityFramework 4 (EF). On the receiving table there is a column of (CreatedDate), which has its default value set to getdate(). So I do not provide it to the EF assuming its value will be defaulted by SQL Server to getdate().

但是这不会发生;相反,EF返回n SaveChanges()的验证错误.

However this doesn't happen; instead EF return a validation error n SaveChanges().

您是否知道发生这种情况的任何原因?请告诉我.

Is there any reason that you know for this happening? Please let me know.

非常感谢.

推荐答案

如果您永远不想编辑该值(例如创建日期),则可以使用:

If you never want to edit that value (like with a created date), you can use:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public virtual DateTime CreatedDate { get; set; }

这将告诉实体框架该值由数据库控制,但仍将获取该值.

This will tell the Entity Framework that the value is controlled by the database, but will still fetch the value.

请注意,随后您将无法更改该值,因此,如果您只想要一个初始值,则不是解决方案.

Note that you then cannot change that value, so it's not a solution if you simply want an initial value.

如果您只想使用默认值,但仍可以对其进行编辑,或者您使用的是Entity Framework 5及更低版本,则必须在代码中设置默认值.

If you just want a default value but are still allowed to edit it, or you are using the Entity Framework 5 and below, you have to set the default in code.

有关此内容的更多讨论:

More discussion about this here:

如何使用来自实体框架中的数据库?

这篇关于EntityFramework不使用默认值更新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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