EF6:打开身份 - 同一 table 中外键的空值

EF6: Switching Identity On - null values for Foreign Keys in this same table

我正在使用此代码进行 EF6 迁移以添加标识:https://romiller.com/2013/04/30/ef6-switching-identity-onoff-with-a-custom-migration-operation/

对于 tables,只有其他 tables 有外键 -> 它工作没有任何问题。

但是对于 table 自己有 FK 的人,我有 null 个值。

示例table(在Update-Database之前):

CREATE TABLE [dbo].[Komponente](
    [KomponenteId] [bigint] NOT NULL,
    [OtherKomponenteId] [bigint] NULL,
 CONSTRAINT [PK_Komponente] PRIMARY KEY CLUSTERED 
(
    [KomponenteId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

示例table(数据库更新后,但未删除old_KomponenteId):

CREATE TABLE [dbo].[Komponente](
    [old_KomponenteId] [bigint] NOT NULL,
    [OtherKomponenteId] [bigint] NULL,
    [KomponenteId] [bigint] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_Komponente] PRIMARY KEY CLUSTERED 
(
    [KomponenteId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

更新来自迁移的 SQL (Update-Database -Verbose):

UPDATE Variante SET KomponenteId = (SELECT TOP 1 KomponenteId FROM Komponente WHERE old_KomponenteId = Variante.KomponenteId) - 这有效,我的 Variante.KomponenteId 已更新值

UPDATE Komponente SET OtherKomponenteId = (SELECT TOP 1 KomponenteId FROM Komponente WHERE old_KomponenteId = Komponente.OtherKomponenteId) - 在此之后,我在 Komponente.OtherKomponenteId

中只有空值

我的迁移:

public override void Up()
{
    this.ChangeIdentity(IdentityChange.SwitchIdentityOn, "Komponente", "KomponenteId")
        .WithDependentColumn("Komponente", "OtherKomponenteId")
        .WithDependentFkName("Komponente", "FK_dbo.Komponente_dbo.Komponente_OtherKomponenteId");
}

好的,我通过将 t2 添加到 SELECT 来解决这个问题。 来自 https://romiller.com/2013/04/30/ef6-switching-identity-onoff-with-a-custom-migration-operation/ 的固定代码:

Generate(new SqlOperation(
    "UPDATE " + item.DependentTable +
    " SET " + item.ForeignKeyColumn +
        " = (SELECT TOP 1 t2." + operation.PrincipalColumn +
        " FROM " + operation.PrincipalTable + " t2" +
        " WHERE t2." + tempPrincipalColumnName + " = " + item.DependentTable + "." + item.ForeignKeyColumn + ")"));

所以现在 SQL 看起来像这样:

UPDATE Komponente SET OtherKomponenteId = (SELECT TOP 1 t2.KomponenteId FROM Komponente t2 WHERE t2.old_KomponenteId = Komponente.OtherKomponenteId)