EF - pass null value to SQL column so default value gets inserted

entity-framework-6 sql-server

Question

SQL Server table T2 has 2 columns:

Id INT NOT NULL 
CreateDate DateTime NOT NULL, default = (getdate())

This statement inserts the CreateDate value correctly because it uses (getdate()) as default.

Insert T2 (Id)
Values (1)

So far so good. The problem is when I use Entity Framework to insert a row and still wish to use the default (getdate()) value.

Because the CreateDate is defined as NOT NULL, I cannot leave it blank or leave out of the Insert statement when using EF. But I want SQL to generate the timestamp on the server/database side.

Is there a way to handle this?

1
2
7/25/2018 9:05:54 PM

Accepted Answer

Thanks to squillman's reference to another SO post, I was able to find the answer.

Go to EDMX diagram, and you can set the StoreGeneratedPattern property to achieve what I am trying to do.

There are three Database Generated Options

Computed : The database generates a value when a row is inserted or updated.
Identity : The database generates a value when a row is inserted.
None : The database does not generate values.

EDIT: Although the picture shows Identity, I had to change it to Computed. The reason is that Identity option only works if the row is Inserted only. If the row is ever updated (other columns updated), then it caused an error. The Computed option seems to work fine with Insert (runs the default script) and Updates (to other columns, default script does not run again).

enter image description here

0
7/28/2018 10:35:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow