Sql表与删除级联共享多个1-many关系

时间:2015-02-17 21:49:44

标签: sql-server database-design

我有一张表可以与2个不同的表之一建立1- *关系。我目前有它设置有2个可空列引用另一个表。但是,这会导致级联删除问题。

CREATE TABLE [dbo].[TA] (
    [Id]               INT                IDENTITY (1, 1) NOT NULL,
    CONSTRAINT [PK_TA] PRIMARY KEY CLUSTERED ([Id] ASC),
);

CREATE TABLE [dbo].[TB] (
    [Id]               INT                IDENTITY (1, 1) NOT NULL,
    [TAId]             INT                NOT NULL,
    CONSTRAINT [FK_TB_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
    CONSTRAINT [PK_TB] PRIMARY KEY CLUSTERED ([Id] ASC),
);

CREATE TABLE [dbo].[TC] (
    [Id]               INT                IDENTITY (1, 1) NOT NULL,
    [TAId]             INT                NULL,
    [TBId]             INT                NULL,
    CONSTRAINT [PK_TC] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_TC_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
    CONSTRAINT [FK_TC_To_TB] FOREIGN KEY ([TBId]) REFERENCES [dbo].[TB] ([Id]), -- NOTE: DELETE CASCADE CAUSES A CIRCULAR REFERENCE
);

基本上,这会创建一个嵌套结构,如:

TA1
 + -- TC1, TC2
 + -- TB1
       + -- TC3, TC4

TC对象应该只是TA或TB(不是两者)的子级。我应该如何开发这个以便我可以删除TA行并删除所有TC和TB引用的行?

1 个答案:

答案 0 :(得分:0)

为了解决这个问题,我最终将[TC]分成多个表described in a blog for entity framework。这创建了以下表结构:

CREATE TABLE [dbo].[TA] (
    [Id]               INT                IDENTITY (1, 1) NOT NULL,
    CONSTRAINT [PK_TA] PRIMARY KEY CLUSTERED ([Id] ASC),
);

CREATE TABLE [dbo].[TB] (
    [Id]               INT                IDENTITY (1, 1) NOT NULL,
    [TAId]             INT                NOT NULL,
    CONSTRAINT [FK_TB_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
    CONSTRAINT [PK_TB] PRIMARY KEY CLUSTERED ([Id] ASC),
);

CREATE TABLE [dbo].[TCA] (
    [Id]               INT                IDENTITY (2, 2) NOT NULL,
    [TAId]             INT                NULL,
    CONSTRAINT [PK_TCA] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_TCA_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
);


CREATE TABLE [dbo].[TCB] (
    [Id]               INT                IDENTITY (1, 2) NOT NULL,
    [TBId]             INT                NULL,
    CONSTRAINT [PK_TCB] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_TCB_To_TB] FOREIGN KEY ([TBId]) REFERENCES [dbo].[TB] ([Id]) ON DELETE CASCADE,
);

我将标识设置为偶数\奇数值,以便在创建两个表的并集时防止冲突(参见上面的链接)。