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

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

错误:

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


当前回答

基本上有两种不同的方法来插入记录而不会出现错误:

1)当IDENTITY_INSERT设置为OFF时。主键“ID”不能出现

2)当IDENTITY_INSERT设置为ON时。主键“ID”必须存在

根据下面的例子,同一个表用IDENTITY主键创建:

CREATE TABLE [dbo].[Persons] (    
    ID INT IDENTITY(1,1) PRIMARY KEY,
    LastName VARCHAR(40) NOT NULL,
    FirstName VARCHAR(40)
);

1)在第一个例子中,当IDENTITY_INSERT是OFF时,你可以插入新的记录到表中而不会得到一个错误。主键“ID”不能出现在“INSERT INTO”语句中,一个唯一的ID值将被自动添加:。如果在这种情况下,ID从INSERT中出现,您将得到错误“不能为表中标识列插入显式值…”

SET IDENTITY_INSERT [dbo].[Persons] OFF;
INSERT INTO [dbo].[Persons] (FirstName,LastName)
VALUES ('JANE','DOE'); 
INSERT INTO Persons (FirstName,LastName) 
VALUES ('JOE','BROWN');

表[dbo]的输出。[人员]将是:

ID    LastName   FirstName
1     DOE        Jane
2     BROWN      JOE

2)在第二个例子中,当IDENTITY_INSERT是ON的时候,你可以插入新的记录到表中而不会得到一个错误。只要ID值不存在,主键“ID”必须从“INSERT INTO”语句中出现:如果ID不存在,在这种情况下,你将得到错误“必须为标识列表指定显式值…”

SET IDENTITY_INSERT [dbo].[Persons] ON;
INSERT INTO [dbo].[Persons] (ID,FirstName,LastName)
VALUES (5,'JOHN','WHITE'); 
INSERT INTO [dbo].[Persons] (ID,FirstName,LastName)
VALUES (3,'JACK','BLACK'); 

表[dbo]的输出。[人员]将是:

ID    LastName   FirstName
1     DOE        Jane
2     BROWN      JOE
3     BLACK      JACK
5     WHITE      JOHN

其他回答

如果您使用Oracle SQL Developer进行连接,请记住添加/sqldev:stmt/

/sqldev:stmt/ set identity_insert TABLE on

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

要非常小心地将IDENTITY_INSERT设置为ON。这是一种糟糕的实践,除非数据库处于维护模式并设置为单用户。这不仅会影响您的插入,还会影响试图访问表的其他人的插入。

为什么要在单位字段中输入一个值?

即使一切正确,如果Identity列的数据类型不是int或long,也会出现此错误。我有单位列为十进制,虽然我只保存int值(我的坏)。更改数据库和底层模型中的数据类型为我解决了这个问题。

如果您使用Interface并以通用方式实现savechanges方法,则会出现使用非类型化DBContext或DBSet的问题

如果这是您的情况,我建议使用强类型的dbcontext

MyDBContext.MyEntity.Add(mynewObject)

那么,保存更改就可以了