代码之家  ›  专栏  ›  技术社区  ›  Vivendi

在标识列上插入值“0”,并让它自动生成标识

  •  0
  • Vivendi  · 技术社区  · 5 年前

    迁移脚本如下所示:

    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 它是自动递增的。

    enter image description here

    Contract ContractCustomer 然后我得到以下错误:

    当identity\u insert设置为OFF时,无法为表“ContractCustomer”中的identity列插入显式值。

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

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

    身份证件 0 . 但它保存变化的部分是在幕后发生的。

    0 让它自己产生 身份证件 号码?或者在我的迁移脚本中有什么可以调整的吗?

    1 回复  |  直到 5 年前
        1
  •  0
  •   SteveC    5 年前

    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;
    
    推荐文章