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

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

错误:

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


当前回答

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

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

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

其他回答

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

/sqldev:stmt/ set identity_insert TABLE on

使用实体框架与这样的模型有同样的问题(我简化了原始代码):

public class Pipeline
{
  public Pipeline()
  {
     Runs = new HashSet<Run>();
  }

  public int Id {get; set;}
  public ICollection<Run> Runs {get;set;}
}

public class Run
{
  public int Id {get; set;}
  public int RequestId {get; set;}
  public Pipeline Pipeline {get;set;}
}

运行与管道有多对1的关系(一个管道可以运行多次)

在我的RunService中,我注入了dbcontext作为上下文。DbContext有一个Runs DbSet。我在RunService中实现了这个方法:

public async Task<Run> CreateAndInit(int requestId, int pplId)
{
  Pipeline pipeline = await pipelineService.Get(pplId).FirstOrDefaultAsync().ConfigureAwait(false);
  Run newRun = new Run {RequestId = requestId, Pipeline = pipeline};
  context.Runs.Add(newRun);
  await context.SaveChangesAsync().ConfigureAwait(false); // got exception in this line
  return newRun;
}

当方法执行时,我得到了这个异常:

Exception has occurred: CLR/Microsoft.EntityFrameworkCore.DbUpdateException
Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll: 'An error occurred while updating the entries. See the inner exception for details.'
 Inner exceptions found, see $exception in variables window for more details.
 Innermost exception     Microsoft.Data.SqlClient.SqlException : Cannot insert explicit value for identity column in table 'Pipelines' when IDENTITY_INSERT is set to OFF.

对我来说,解决方案是将对象和关系的创建分开

public async Task<Run> CreateAndInit(int requestId, int pplId)
{
  Pipeline pipeline = await pipelineService.Get(pplId).FirstOrDefaultAsync().ConfigureAwait(false);
  Run newRun = new Run {RequestId = requestId};
  context.Runs.Add(newRun);
  newRun.Pipeline = pipeline; // set the relation separately
  await context.SaveChangesAsync().ConfigureAwait(false); // no exception
  return newRun;
}

请注意,如果您用;结束每一行,SET IDENTITY_INSERT mytable ON命令将不适用于以下行。

即。 像这样的查询

SET IDENTITY_INSERT mytable ON;
INSERT INTO mytable (VoucherID, name) VALUES (1, 'Cole');

给出错误 当IDENTITY_INSERT设置为OFF时,无法为表'mytable'中的身份列插入显式值。

但是像这样的查询是可以的:

SET IDENTITY_INSERT mytable ON
INSERT INTO mytable (VoucherID, name) VALUES (1, 'Cole')
SET IDENTITY_INSERT mytable OFF;

SET IDENTITY_INSERT命令似乎只适用于事务,而;将表示事务的结束。

如果你在SQL服务器上得到这个错误,然后运行这个查询-

SET IDENTITY_INSERT tableName ON

这只适用于数据库的一个表 例:如果表名是student,那么查询如下:

SET IDENTITY_INSERT student ON

如果你在你的web应用程序或你使用实体框架得到这个错误,那么首先在SQL服务器上运行这个查询,并更新你的实体模型(。Edmx文件)并构建您的项目,此错误将被解决

每个人都评论SQL,但是在EntityFramework中发生了什么?我看了整篇文章,没人能解出EF。所以几天后,我找到了一个解决方案: 在EF Core的上下文中创建模型有这样一条指令:modelBuilder。实体<客户端>(实体=>{实体。属性(e => e.d id).ValueGeneratedNever();

这也会产生错误,解决方案:你必须通过ValueGeneratedOnAdd()改变它的工作!