How do I tell Entity Framework to allow SQL Server to provide a defined default value for a field?

拥有回忆 提交于 2019-12-23 06:41:39

问题


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

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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/11173162/how-do-i-tell-entity-framework-to-allow-sql-server-to-provide-a-defined-default

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