使用继承表时,我遇到了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
注意 ON DELETE NO ACTION
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
注意 ON DELETE CASCADE
那是相当重要的......
答案 0 :(得分: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
注意 ON DELETE NO ACTION
<强> 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
注意 ON DELETE CASCADE
将这些更改应用到数据库后,我可以毫无问题地删除。