在标识列中插入值“ 0”,并使其自动生成标识

问题描述

我正在使用名为AspNetZero的应用程序(类似于AspNet Boilerplate),并且在此应用程序中创建了迁移脚本。

迁移脚本如下:

migrationBuilder.CreateTable(
    name: "ContractCustomer",columns: table => new
    {
        ContractId = table.Column<int>(nullable: false),CustomerId = table.Column<int>(nullable: false),Id = table.Column<int>(nullable: false).Annotation("sqlServer:Identity","1,1"),CreationTime = table.Column<DateTime>(nullable: false),},constraints: table =>
    {
        table.UniqueConstraint("UX",x => new {x.ContractId,x.VerzorgerId});
        table.PrimaryKey("PK_ContractVerzorger",x => x.Id);
    });

因此,这会在自动Id上创建一个带有primaryy键的表。

enter image description here

但是事实是,使用AspNetZero,事情在幕后对您来说有点自动化。当我尝试使用Contract插入ContractCustomer时,出现以下错误

当IDENTITY_INSERT设置为OFF时,无法为表'ContractCustomer'中的标识列插入显式值。

当我使用sql Server Profiler时,我看到它正在尝试运行以下查询

INSERT INTO [ContractCustomer] ([Id],[ContractId],[CustomerId],[CreationTime])
VALUES (0,2,1,'2020-09-12 13:33:54.2629678');

因此,明确地将Id设置为0。但是,保存更改的部分是在后台进行的。

是否有一种方法可以告诉sql Server忽略0并让其生成自己的Id数字?还是我可以在迁移脚本中进行调整以使其正常工作?

解决方法

一种快速解决此问题的方法是创建INSTEAD OF触发器。然后只需从要执行的实际INSERT中删除ID和0。像这样

drop trigger if exists trg_ContractCustomer_instead_of_ins;
go
create trigger trg_ContractCustomer_instead_of_ins on [ContractCustomer]
instead of insert
as
set nocount on;
if exists(select * from inserted)
    INSERT INTO [ContractCustomer] ([ContractId],[CustomerId],[CreationTime])
    select [ContractId],[CreationTime] from inserted;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...