0

在使用继承表时,我遇到了 ON DELETE CASCADE 的问题。

我有以下表格(模型优先) 数据库模型

现在,如果我想删除 Entity1 中的一个条目。

using (var ctx = new MyEntities())
{
   var first = ctx.Entity1Set.First();
   ctx.DeleteObject(first);
   ctx.SaveChanges();
}

简单...但是 SaveChanges 引发以下异常。

DELETE 语句与 REFERENCE 约束 FK_EntityA_inherits_BaseEntity 冲突。冲突发生在数据库“MyDB”、表“dbo.BaseEntitySet_EntityA”、列“Id”中。语句已终止。

我该如何解决?


更新

我注意到 VS2010 和 VS2012 模型设计器输出 SQL 的方式有所不同。

VS2010

-- Creating foreign key on [Id] in table 'BaseEntitySet_EntityA'
ALTER TABLE [dbo].[BaseEntitySet_EntityA]
ADD CONSTRAINT [FK_EntityA_inherits_BaseEntity]
    FOREIGN KEY ([Id])
    REFERENCES [dbo].[BaseEntitySet]
        ([Id])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

-- Creating foreign key on [Id] in table 'BaseEntitySet_EntityB'
ALTER TABLE [dbo].[BaseEntitySet_EntityB]
ADD CONSTRAINT [FK_EntityB_inherits_BaseEntity]
    FOREIGN KEY ([Id])
    REFERENCES [dbo].[BaseEntitySet]
        ([Id])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

删除通知不采取行动

VS2012

-- Creating foreign key on [Id] in table 'BaseEntitySet_EntityA'
ALTER TABLE [BaseEntitySet_EntityA]
ADD CONSTRAINT [FK_EntityA_inherits_BaseEntity]
    FOREIGN KEY ([Id])
    REFERENCES [BaseEntitySet]
        ([Id])
    ON DELETE CASCADE ON UPDATE NO ACTION;
GO

-- Creating foreign key on [Id] in table 'BaseEntitySet_EntityB'
ALTER TABLE [BaseEntitySet_EntityB]
ADD CONSTRAINT [FK_EntityB_inherits_BaseEntity]
    FOREIGN KEY ([Id])
    REFERENCES [BaseEntitySet]
        ([Id])
    ON DELETE CASCADE ON UPDATE NO ACTION;
GO

关于删除级联的通知

那是相当有意义的...

4

1 回答 1

0

Visual Studio 2010 ADO 实体设计器中似乎存在一个错误,导致生成不正确的 SQL。

VS2010:

-- Creating foreign key on [Id] in table 'BaseEntitySet_EntityA'
ALTER TABLE [dbo].[BaseEntitySet_EntityA]
ADD CONSTRAINT [FK_EntityA_inherits_BaseEntity]
    FOREIGN KEY ([Id])
    REFERENCES [dbo].[BaseEntitySet]
        ([Id])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

-- Creating foreign key on [Id] in table 'BaseEntitySet_EntityB'
ALTER TABLE [dbo].[BaseEntitySet_EntityB]
ADD CONSTRAINT [FK_EntityB_inherits_BaseEntity]
    FOREIGN KEY ([Id])
    REFERENCES [dbo].[BaseEntitySet]
        ([Id])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

删除通知不采取行动

VS2012

-- Creating foreign key on [Id] in table 'BaseEntitySet_EntityA'
ALTER TABLE [BaseEntitySet_EntityA]
ADD CONSTRAINT [FK_EntityA_inherits_BaseEntity]
    FOREIGN KEY ([Id])
    REFERENCES [BaseEntitySet]
        ([Id])
    ON DELETE CASCADE ON UPDATE NO ACTION;
GO

-- Creating foreign key on [Id] in table 'BaseEntitySet_EntityB'
ALTER TABLE [BaseEntitySet_EntityB]
ADD CONSTRAINT [FK_EntityB_inherits_BaseEntity]
    FOREIGN KEY ([Id])
    REFERENCES [BaseEntitySet]
        ([Id])
    ON DELETE CASCADE ON UPDATE NO ACTION;
GO

关于删除级联的通知

将这些更改应用于数据库后,我可以毫无问题地删除。

于 2013-04-05T09:53:54.163 回答