How to insert default DB values ​​in EF?

when adding a new entry like this

ContentContacts c2 = new ContentContacts(); c2.updated_user = c2.created_user = loggedUserId; c2.created_date = c2.updated_date = DateTime.UtcNow; db.ContentContacts.AddObject(c2); 

I get

Cannot insert NULL value in column "main_email_support", table "SQL2008R2.dbo.ContentContacts"; column does not allow zeros. INSERT fails. Application completed.

but the default value in the database is an empty string, for example:

alt text

Why am I getting such an error? EF shouldn't say something like:

"ohh, this is null , so instead add the default value in the column:

+7
entity-framework
source share
1 answer

I did a little test, created a table with a column that had a default value but did not allow null.

Then this is an SQL expression:

 INSERT INTO [Test].[dbo].[Table_1] ([TestText]) VALUES (null) 

Gives this error:

Msg 515, Level 16, State 2, Line 1
Cannot insert a NULL value in the column "TestText", table 'Test.dbo.Table_1'; column does not allow zeros. INSERT does not work.

The problem is that the insert indicates all columns, as well as those that have default values. Insert tries to update columns with null values.

You have 2 options:

  • Refresh a table through a view that does not contain default columns
  • Set default values ​​in C # code

The default is business logic, so there is a case where it is set at the business level of your application.

+6
source share

All Articles