Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot insert the value null into column ... when the value is not null

in my c# code I have an insert into my DB, but it throws an exception

Cannot insert the value NULL into column 'BoxID', table 'Moroccanoil_Replicated.dbo.Boxes'; column does not allow nulls. INSERT fails.

however when debugging this piece of code I see that the box is actually not null, therther more when i test the same exact insert in my SQL SM It works just fine.

Edit:

For some reason this is the query that is actually being executed according to the profiler :

exec sp_executesql 
  N'INSERT [dbo].[Boxes]([MasterBoxID], [DateTime], [Reported], [StationID])
  VALUES (NULL, @0, @1, @2)
  SELECT [BoxID]
  FROM [dbo].[Boxes]
  WHERE @@ROWCOUNT > 0 AND [BoxID] = scope_identity()',
  N'@0 datetime2(7),@1 bit,@2 int',@0='2015-11-30 13:37:46.4714394',@1=0,@2=7

Does anyone know why is this and how to fix it?

More relevant information :

  • The exception occurs on the db.SaveChanges() call and not on the insert.
  • The BoxID is not defined as identity.

Here is the code in debug mode with the inserted values: enter image description here

And the same insert in SQL that works just fine: enter image description here

like image 756
Ravid Goldenberg Avatar asked Oct 12 '25 21:10

Ravid Goldenberg


1 Answers

As mentioned in comments:

Most likely EF won't pass the ID parameter because it thinks the value is created by the database. This means you should turn off DatabaseGeneratedOptions.Identity for this column.

With DatabaseGeneratedOption.Identity, EF won't pass the ID value to the database because it suspects it to be given by DBMS. This can lead to this issue or an DbUpdateConcurrencyException, when it suspects an object with a given Id value to be in the database, but it was actually altered by DBMS.

like image 51
DevilSuichiro Avatar answered Oct 14 '25 09:10

DevilSuichiro