我首先使用实体框架 5 模型。
我的模型中有一些实体,其中大多数实体具有一对多的关系,删除和更新时具有“无操作”外键约束。
但我仍然能够毫无错误地删除父对象和子对象(在 EF4 上,我曾经收到一个异常警告,指出我无法删除一个对象,因为有另一个对象引用它)
先EF5模型生成的部分代码:
...
... Create all tables...
...
... Create all foreign key constraints ...
...
-- Creating foreign key on [TEstTela_ID] in table 'TEstPermissao'
ALTER TABLE [dbo].[TEstPermissao]
ADD CONSTRAINT [FK_TEstTelaTEstPermissao]
FOREIGN KEY ([TEstTela_ID])
REFERENCES [dbo].[TEstTela]
([ID])
ON DELETE NO ACTION ON UPDATE NO ACTION;
....
删除对象代码:
...
EstContextDB CurrentContext = new EstContextDB(); // inherits from DbContext
CurrentContext.Set<TEstTela>().Remove(currentTEstTelaEntity);
CurrentContext.SaveChanges(); /* Exception should be thrown here
because at least one TEstPermissao object references this
currentTEstTelaEntity but it still delete the object without
errors or exceptions, and plus the TEstPermissao object
that references this currentTEstTelaEntity gets its reference as 'null' */