当值不为null时,无法将null插入列... [英] cannot insert the value null into column ... when the value is not null

查看:56
本文介绍了当值不为null时,无法将null插入列...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#代码中,我在数据库中插入了一个插入,但是它引发了异常

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

无法将值NULL插入表"Moroccanoil_Replicated.dbo.Boxes"的"BoxID"列中;列不允许为空.INSERT失败.

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

但是,当调试这段代码时,我看到该框实际上不是null,而当我在SQL SM中测试相同的完全插入时,它的作用就更大了.

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.

由于某种原因,这是根据探查器实际执行的查询:

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?

更多相关信息:

  • 该异常发生在db.SaveChanges()调用上,而不发生在插入上.
  • BoxID未定义为身份.

这是调试模式下的代码,其中插入了值:

Here is the code in debug mode with the inserted values:

并且在SQL中的相同插入效果也很好:

And the same insert in SQL that works just fine:

推荐答案

如注释中所述:

最有可能的EF不会传递ID参数,因为它认为该值是由数据库创建的.这意味着您应为此列关闭DatabaseGeneratedOptions.Identity.

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.

使用DatabaseGeneratedOption.Identity,EF不会将ID值传递给数据库,因为它怀疑它是由DBMS给出的.当它怀疑具有给定Id值的对象位于数据库中,但实际上已被DBMS更改时,这可能导致此问题或DbUpdateConcurrencyException.

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.

这篇关于当值不为null时,无法将null插入列...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆