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自动递增主键的表。

在此处输入图像描述

但问题是,使用 AspNetZero,您可以在幕后进行一些自动化操作。当我尝试Contract使用 a插入 a 时,出现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');

所以它明确地将 设置Id0。但是它保存更改的部分发生在幕后。

有没有办法告诉 SQL Server 忽略0并让它生成自己的Id号码?或者我可以在迁移脚本中进行一些调整以使其正常工作?

4

1 回答 1

0

快速解决此问题的一种方法是创建一个 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], [CustomerId], [CreationTime] from inserted;
于 2020-09-12T12:22:03.370 回答