简体   繁体   English

在标识列上插入值 '0' 并让它自动生成一个标识

[英]Insert value '0' on identity column and let it auto-generate an identity

I'm using an application called AspNetZero (much like AspNet Boilerplate) and I created a migration script in this application.我正在使用一个名为 AspNetZero(很像 AspNet Boilerplate)的应用程序,我在这个应用程序中创建了一个迁移脚本。

The migration script looks like this:迁移脚本如下所示:

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);
    });

So this creates a table with a primarey key on Id which is auto incremented.因此,这将创建一个表,其中Id的主键是自动递增的。

在此处输入图片说明

But the thing is, with AspNetZero things are a bit automated behind the scenes for you.但问题是,有了 AspNetZero,事情在幕后对你来说有点自动化。 When I try to insert a Contract with a ContractCustomer I then get the following error:当我尝试与ContractCustomer插入Contract ,我收到以下错误:

Cannot insert explicit value for identity column in table 'ContractCustomer' when IDENTITY_INSERT is set to OFF.当 IDENTITY_INSERT 设置为 OFF 时,无法为表“ContractCustomer”中的标识列插入显式值。

When I use SQL Server Profiler I see that it is trying to run the following query:当我使用 SQL Server Profiler 时,我看到它正在尝试运行以下查询:

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

So it is explicity setting the Id to 0 .所以它明确地将Id设置为0 But the part where it saves the changes is happening behind the scenes.但它保存更改的部分发生在幕后。

Is there a way to tell SQL Server to ignore the 0 and let it generate its own Id number?有没有办法告诉 SQL Server 忽略0并让它生成自己的Id号? Or is there something I can adjust in my migrations script to get this to work?或者我可以在我的迁移脚本中调整一些东西来让它工作吗?

One way to quickly solve this would be to create an INSTEAD OF trigger.快速解决此问题的一种方法是创建 INSTEAD OF 触发器。 Then just remove the ID and 0 from the actual INSERT that gets executed.然后只需从执行的实际 INSERT 中删除 ID 和 0。 Something like this像这样的东西

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM