EF Core DB-first:如何在没有级联删除的情况下删除依赖项?

问题描述

(示例代码贴在最后。)

我使用的是 EF Core 5 数据库优先(即逆向工程 POCO)。使用 .Remove()删除”集合中的项目时,后续 SaveChanges() 会抱怨孤儿。是的,可以找到很多关于此的问答。

对于代码优先的场景,可以将其添加到配置中(来自 here):

modelBuilder.Entity<Child>.HasKey(t => new { t.ParentId,t.ChildId });

但对于 DB-first 来说并不实用。如果数据库为 FK 关系(docs reference here)设置了级联删除生成的模型[更正]包括

entity.OnDelete(DeleteBehavior.ClientSetNull)

删除(使用 .Remove()确实有效,包括 SaveChanges()。但是……

在这里面临的问题是,这个“解决方案”要求我们所有的 FK 关系都配置为在数据库中使用级联删除。哎呀!数据完整性对我们很重要,并且使用 UNIQUE 约束和不可为空的 FK 关系来保护它之前已经拯救了我们。不设置级联删除是一种类似的保护措施,仅在关系断开的情况下使用它可以说是矫枉过正。

因此,转到第三个选项:显式删除孤立的子项,注意我在描述的第二个项目符号 here 中。我所需要的只是旧的 ObjectContext.DeleteObject(),但没有等效的 EF Core。

问:如何删除该子项?如果不可能,我还有其他选择吗?

下面是一个简单的例子,它在代码中栩栩如生:

//Create a parent with two children
var db = new Context();            
var newParent = new Parent() {Name = "NewParent"+DateTime.Now.Second};
db.Parents.Add(newParent);
newParent.Children = new List<Child>() {new Child() {Name="ChildOne"},new Child() {Name="ChildTwo"}};
db.SaveChanges();
db.dispose();

//Pick a parent item and delete one child item
var db2 = new Context();
var Parent = db2.Parents.First();
db2.Entry(Parent).Collection(f => f.Children).Load();
var ChildToDelete = Parent.Children.First();
Parent.Children.Remove(ChildToDelete);
db2.SaveChanges(); // -----> FAILS with "The association between entity types 'Parent' 
                   // and 'Child' has been severed,but the relationship is either marked
                   //  as required or is implicitly required because the foreign key 
                   // is not nullable."

表格本质上是

CREATE TABLE [dbo].[Child](
    [ChildId] [int] IDENTITY(1,1) NOT NULL,[ParentId] [int] NOT NULL,[Name] [nchar](20) NOT NULL,CONSTRAINT [PK_Child] PRIMARY KEY CLUSTERED)

CREATE TABLE [dbo].[Parent](
    [ParentId] [int] IDENTITY(1,CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED)

ALTER TABLE [dbo].[Child]  WITH CHECK ADD  CONSTRAINT [FK_Child_Parent] FOREIGN KEY([ParentId])
REFERENCES [dbo].[Parent] ([ParentId])
ALTER TABLE [dbo].[Child] CHECK CONSTRAINT [FK_Child_Parent]

解决方法

而不是从父级的集合中移除子级

Parent.Children.Remove(ChildToDelete);

删除孩子

db.Set<Child>().Remove(ChildToDelte);