Database default value is not inserted while create record by entity framework

asp.net-mvc c# entity-framework sql-server-2008-r2

Question

I have a LoginRecord table in sqlserver 2008 with the following column structure-

LoginId      - int, identity
UserId       - int
LoginDateTime- Allow nulls false,default value getdate()

I am inserting new record by entity framework 6 as below-

 db.LoginRecords.Add(new LoginRecord() { UserId = UserId }); 
 db.SaveChanges();

But in LoginDateTime table, null value is being inserted. It supposed to be current datetime.

I am using database first approach.

How can overcome this issue?

1
8
3/16/2014 11:12:37 PM

Accepted Answer

Combined my two comments into an answer.

Try setting the "StoredGeneratedPattern" attribute of your datetime in the EDMX file to Computed. From the following thread: http://www.stackoverflow.com/a/4688135/2488939

To do this, go to the edmx file designer by clicking on your edmx file. Then locate your table and the property. Right-click the column in the table that you want to change and click on properties. The property window should then come up and you will see as one of the properties "StoredGeneratedPattern". Change that to computed.

7
3/14/2018 5:19:24 PM

Popular Answer

In addition to changing the EDMX file as suggested by Vishwaram Maharaj, you should make the definition of the table match between EF and the DB. The table description of "LoginDateTime- Allow nulls false" is itself false. The field clearly allows NULLs if NULLs are being inserted. Alter the column to not allow NULL if it truly shouldn't have NULL values in it:

ALTER TABLE LoginRecords ALTER COLUMN LoginDateTime DATETIME NOT NULL;


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