当我执行下面的脚本时,我有以下错误。错误是关于什么,如何解决?
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'中的标识列插入显式值。
当前回答
首先…
首先,您需要知道为什么会出现错误。
让我们以一个简单的JSON数据HttpPost为例,如下所示:
{
"conversationID": 1,
"senderUserID": 1,
"receiverUserID": 2,
"message": "I fell for the wrong man!",
"created":"2022-02-14T21:18:11.186Z"
}
如果你在连接到SQLServer或任何其他数据库服务器时使用Entity框架核心生成数据库,数据库将自动负责更新和自动生成标识列的Key/Unique标识符,在大多数情况下,这是一个由它自动递增的整数值。
为了使用内置的约定安全地发布数据,可以将ID字段从想要发送到数据库的数据中删除,并让数据库引擎和ef-core完成它们设计的繁重工作。
所以发布数据的正确方式是:
{
"senderUserID": 1,
"receiverUserID": 2,
"message": "I fell for the wrong man!",
"created":"2022-02-14T21:18:11.186Z"
}
你会注意到我拿出了ConversationID。
你可以在这个网站上了解更多关于实体框架的信息:https://entityframeworkcore.com
我希望您在应用程序中更多地遵循约定,而不是配置。知道如何按照已经被证实的标准和惯例做事将为您节省大量的工作时间。
其他回答
您正在为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
如果您使用Oracle SQL Developer进行连接,请记住添加/sqldev:stmt/
/sqldev:stmt/ set identity_insert TABLE on
我使用asp.net core 5.0,我得到这个错误。我得到这个错误,因为我添加了另一个数据并触发了另一个.SaveChanges()方法,如下所示:
_unitOfWorkVval.RepositoryVariantValue.Create(variantValue);
int request = HttpContext.Response.StatusCode;
if (request == 200)
{
int tryCatch = _unitOfWorkCVar.Complete();
if (tryCatch != 0)
{
productVariant.CategoryVariantID = variantValue.CategoryVariantID;
productVariant.ProductID = variantValue.ProductID;
productVariant.CreatedDate = DateTime.Now;
_unitOfWorkProductVariant.RepositoryProductVariant.Create(productVariant);
_unitOfWorkVval.RepositoryVariantValue.Create(variantValue);
int request2 = HttpContext.Response.StatusCode;
if(request==200)
{
int tryCatch2=_unitOfWorkProductVariant.Complete();//The point where i get that error
}///.......
即使一切正确,如果Identity列的数据类型不是int或long,也会出现此错误。我有单位列为十进制,虽然我只保存int值(我的坏)。更改数据库和底层模型中的数据类型为我解决了这个问题。
不要给OperationID赋值,因为它会自动生成。试试这个:
Insert table(OpDescription,FilterID) values ('Hierachy Update',1)