开发者

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 th开发者_运维技巧e database is an empty string like:

How to insert DB Default values under EF?

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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜