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

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

错误:

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


当前回答

最好的解决方案是使用GeneratedValue(strategy =…)注释,即。

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column ...
private int OperationID;

它说,这个列是由数据库使用IDENTITY策略生成的,你不需要关心-数据库会做的。

其他回答

在您的查询中有前面提到的OperationId,它不应该在那里,因为它是自动递增的

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

所以你的问题是

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

您正在为OperationId插入值,这是一个标识列。

您可以像这样在表上打开标识插入,以便您可以指定自己的标识值。

SET IDENTITY_INSERT Table1 ON

INSERT INTO Table1
/*Note the column list is REQUIRED here, not optional*/
            (OperationID,
             OpDescription,
             FilterID)
VALUES      (20,
             'Hierachy Update',
             1)

SET IDENTITY_INSERT Table1 OFF 

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

设置该字段的身份增量时,不能在“OperationID”列中插入数据。

不要在该字段中输入值,它将自动设置。

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

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)]