Why is EF DataBase First not use getdate()?

爱⌒轻易说出口 提交于 2019-12-07 06:07:28

问题


I am using EF 4.1 with database first.

Example table:

CREATE TABLE dbo.Product(
   [ID] [int] IDENTITY(1,1) not null,
   Title nvarchar(200) not null,
   CreateDate datetime not null default(getdate()),
)

When I add a new row, I get an exception about DateTime type overflow.

The getdate() of database settings is invalid.

I must be set the storeGeneatePattern property of the createdate field to Computed.

Is there any way to let the EF automatically generated the DateTime column without manually set??


回答1:


No EF will never use your database default. The reason is that your entity has non nullable DateTime property. This property has by default assigned default value in .NET which is 1.1.0001. EF doesn't know if you assigned that value or if it is default value so it always explicitly passes this value to the database. Same happens if you use nullable type but in this case EF will pass explicitly null. In both cases default value from database will not be applied because that value is applied only when the value from application is not explicitly passed in an insert command - EF explicitly passes all values from entity.




回答2:


You can do it in your Product entity class constructor,

public class Product{
  public Product(){
     CreateDate =DateTime.Now;
  }
}


来源:https://stackoverflow.com/questions/10292179/why-is-ef-database-first-not-use-getdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!