Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert DB Default values under EF?

when adding a new record 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'm getting

Cannot insert the value NULL into column 'main_email_support', table 'SQL2008R2.dbo.ContentContacts'; column does not allow nulls. INSERT fails. The statement has been terminated.

but the default value in the database is an empty string like:

alt text

why am I getting such error? shouldn't the EF says something like:

"ohh, it's a nullvalue, so let's add the column default value instead"

like image 999
balexandre Avatar asked Nov 13 '10 11:11

balexandre


1 Answers

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

Then this SQL Statement:

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

Gives this error:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'TestText', table 'Test.dbo.Table_1'; column does not allow nulls. INSERT fails.

The problem here is that the insert specifies all the columns, also those with default values. The the Insert tries to update the columns with null values.

You have 2 options:

  • Update the table through a view, which does not contain the default columns
  • Set the default values in your C# code

A default value is business logic, so there is a case for it being set in the business layer of your application.

like image 97
Shiraz Bhaiji Avatar answered Nov 11 '22 14:11

Shiraz Bhaiji