当我执行下面的脚本时,我有以下错误。错误是关于什么,如何解决?
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'中的标识列插入显式值。
当前回答
如果您正在使用liquibase更新SQL Server,则可能试图将记录键插入到autoIncrement字段中。通过从插入中删除列,脚本应该可以运行。
<changeSet id="CREATE_GROUP_TABLE" >
<createTable tableName="GROUP_D">
<column name="GROUP_ID" type="INTEGER" autoIncrement="true">
<constraints primaryKey="true"/>
</column>
</createTable>
</changeSet>
<changeSet id="INSERT_UNKNOWN_GROUP" >
<insert tableName="GROUP_D">
<column name="GROUP_ID" valueNumeric="-1"/>
...
</insert>
</changeSet>
其他回答
EF Core 3.x
引用Leniel Maccaferri,我有一个带有自动递增属性的表,称为ID(原始主键)和另一个属性称为Other_ID(新的主键)。最初ID是主键,但后来Other_ID需要成为新的主键。由于ID正在应用程序的其他部分使用,我不能只是从表中删除它。Leniel Maccaferri解决方案只适用于我之后,我添加了以下片段:
entity.HasKey(x => x.Other_ID);
entity.Property(x => x.ID).ValueGeneratedOnAdd();
完整代码片段如下(ApplicationDbContext.cs):
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
builder.Entity<tablename>(entity =>
{
entity.HasKey(x => x.Other_ID);
entity.Property(x => x.ID).ValueGeneratedOnAdd();
entity.HasAlternateKey(x => new { x.Other_ID, x.ID });
});
}
在该表的实体中,将DatabaseGenerated属性添加到标识插入设置的列之上:
例子:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TaskId { get; set; }
首先…
首先,您需要知道为什么会出现错误。
让我们以一个简单的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
我希望您在应用程序中更多地遵循约定,而不是配置。知道如何按照已经被证实的标准和惯例做事将为您节省大量的工作时间。
使用实体框架与这样的模型有同样的问题(我简化了原始代码):
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;
}
如果你在SQL服务器上得到这个错误,然后运行这个查询-
SET IDENTITY_INSERT tableName ON
这只适用于数据库的一个表 例:如果表名是student,那么查询如下:
SET IDENTITY_INSERT student ON
如果你在你的web应用程序或你使用实体框架得到这个错误,那么首先在SQL服务器上运行这个查询,并更新你的实体模型(。Edmx文件)并构建您的项目,此错误将被解决