问题描述
我正在使用名为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);
});
但是事实是,使用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;