当我执行下面的脚本时,我有以下错误。错误是关于什么,如何解决?
Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)
错误:
服务器:Msg 544,级别16,状态1,线路1 当IDENTITY_INSERT设置为OFF时,无法为表'table'中的标识列插入显式值。
当我执行下面的脚本时,我有以下错误。错误是关于什么,如何解决?
Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)
错误:
服务器:Msg 544,级别16,状态1,线路1 当IDENTITY_INSERT设置为OFF时,无法为表'table'中的标识列插入显式值。
当前回答
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)]
其他回答
在我的情况下,我插入了比表中定义的更多的字符。
在我的表列用nvarchar(3)定义,我传递了超过3个字符,同样的错误消息来了。
这不是答案,但在某些情况下可能是类似的问题
要非常小心地将IDENTITY_INSERT设置为ON。这是一种糟糕的实践,除非数据库处于维护模式并设置为单用户。这不仅会影响您的插入,还会影响试图访问表的其他人的插入。
为什么要在单位字段中输入一个值?
首先转到所需的表名
步骤2 ->右击表名
选择设计
单击列名
步骤5)进入列属性,然后将No设置为Identity Specification
[注意:插入到显式值后,如果你想,你可以恢复到标识规范为true,然后它会再次生成值]
如果你使用SQL server管理studio你可以使用下面的方法
步骤1) 步骤2)
即使一切正确,如果Identity列的数据类型不是int或long,也会出现此错误。我有单位列为十进制,虽然我只保存int值(我的坏)。更改数据库和底层模型中的数据类型为我解决了这个问题。
在我的例子中,我已经在modelBuilder的上下文中设置了另一个属性作为键。
modelBuilder.Entity<MyTable>().HasKey(t => t.OtherProp);
我必须设置正确的id
modelBuilder.Entity<MyTable>().HasKey(t => t.Id);