0

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?

2
  • Change from Entity Framework to a sensible solution :) heheh Commented Jun 23, 2012 at 21:35
  • Well Andomar, that would be a very dramatic change. I was looking for a smaller one! Commented Jun 23, 2012 at 22:59

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that is supposed to solve the problem. But unfortunately I got the same exception again although I set StoreGeneratedPattern to Identity. The exception again tells me that SQL can't accept #12:00:00 AM# as a valid value, meaning EF is still sending the .NET default to SQL. Anything else I should be careful with?
Open EDMX file as XML and check that the pattern is correctly set in both CSDL part and SSDL part of the mapping file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.