微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在标识列中插入值“ 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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?