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

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

错误:

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


当前回答

在您的查询中有前面提到的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 

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

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;
}

在我的例子中,问题是,当我试图更新记录时,我自己从代码中指定了自增ID。 在从新记录创建中删除ID属性之后,一切都正常了。

不要给OperationID赋值,因为它会自动生成。试试这个:

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

在我的情况下,我插入了比表中定义的更多的字符。

在我的表列用nvarchar(3)定义,我传递了超过3个字符,同样的错误消息来了。

这不是答案,但在某些情况下可能是类似的问题