当我执行下面的脚本时,我有以下错误。错误是关于什么,如何解决?
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'中的标识列插入显式值。
当前回答
如果你在SQL服务器上得到这个错误,然后运行这个查询-
SET IDENTITY_INSERT tableName ON
这只适用于数据库的一个表 例:如果表名是student,那么查询如下:
SET IDENTITY_INSERT student ON
如果你在你的web应用程序或你使用实体框架得到这个错误,那么首先在SQL服务器上运行这个查询,并更新你的实体模型(。Edmx文件)并构建您的项目,此错误将被解决
其他回答
另一种情况是检查主键是否与你的类名称相同,唯一的区别是你的主键有一个'ID'附加在它上面,或者在与类如何命名无关的主键上指定[Key]。
我不确定“插入表”的用途是什么,但如果你只是想插入一些值,请尝试:
Insert Into [tablename] (OpDescription,FilterID)
values ('Hierachy Update',1);
我有同样的错误消息出现,但我认为这应该工作。只要是主键,ID就应该自动递增。
使用实体框架与这样的模型有同样的问题(我简化了原始代码):
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;
}
在该表的实体中,将DatabaseGenerated属性添加到标识插入设置的列之上:
例子:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TaskId { get; set; }
只需删除拖放到.dbml文件中的表,然后重新拖动它们。清洁方案>重建方案>重建方案。
这对我很管用。
我没有做我自己的表格,我是用VS和SSMS,我遵循这个链接为ASP。净身份:https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project