当我执行下面的脚本时,我有以下错误。错误是关于什么,如何解决?

Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)

错误:

服务器:Msg 544,级别16,状态1,线路1 当IDENTITY_INSERT设置为OFF时,无法为表'table'中的标识列插入显式值。


当前回答

我不确定“插入表”的用途是什么,但如果你只是想插入一些值,请尝试:

Insert Into [tablename] (OpDescription,FilterID)
values ('Hierachy Update',1);

我有同样的错误消息出现,但我认为这应该工作。只要是主键,ID就应该自动递增。

其他回答

你可以简单地使用这句话,例如,如果你的表名是学校。 在插入之前,确保identity_insert设置为ON,在插入查询之后,将identity_insert设置为OFF

SET IDENTITY_INSERT School ON
/*
  insert query
  enter code here
*/
SET IDENTITY_INSERT School OFF

另一种情况是检查主键是否与你的类名称相同,唯一的区别是你的主键有一个'ID'附加在它上面,或者在与类如何命名无关的主键上指定[Key]。

把断点放在你的[HttpPost]方法上,检查什么值被传递给Id属性。如果它不为零,则会发生此错误。

在我的例子中,问题是,当我试图更新记录时,我自己从代码中指定了自增ID。 在从新记录创建中删除ID属性之后,一切都正常了。

This occurs when you have a (Primary key) column that is not set to Is Identity to true in SQL and you don't pass explicit value thereof during insert. It will take the first row, then you wont be able to insert the second row, the error will pop up. This can be corrected by adding this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)] in your PrimaryKey column and make sure its set to a data type int. If the column is the primary key and is set to IsIDentity to true in SQL there is no need for this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)] this also occurs when u have a column that is not the primary key, in SQL that is set to Is Identity to true, and in your EF you did not add this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)]