C# 通过一对多删除孤立项
我有以下代码:C# 通过一对多删除孤立项,c#,entity-framework,C#,Entity Framework,我有以下代码: public class Parent { public int ParentId {get;set;} public ICollection<Child> Children {get;set;} } public class Child { public int ChildId {get;set;} public Parent Parent {get;set;} } 公共类父类 { public int ParentId{ge
public class Parent
{
public int ParentId {get;set;}
public ICollection<Child> Children {get;set;}
}
public class Child
{
public int ChildId {get;set;}
public Parent Parent {get;set;}
}
公共类父类
{
public int ParentId{get;set;}
公共ICollection子项{get;set;}
}
公营儿童
{
public int ChildId{get;set;}
公共父级{get;set;}
}
EF将其映射为一对多,无需任何额外努力。当我用新集合(另外3个项目)替换子集合时,子表中的旧孤立实体如下所示:
Id | Parent_Id
1 NULL <-- orphan
2 NULL <-- orphan
3 NULL <-- orphan
4 1 <-- new
5 1 <-- new
6 1 <-- new
Id |父| Id
1 NULL据我所知,要识别关系,您需要包含作为子项主键一部分的父项主键。EF将允许您从集合中删除子项并为您删除它
仅仅拥有导航属性是行不通的。标识关系是数据库级别的概念,因此需要公开的主键id
在我的应用程序中,我有一个类似的模型。然而,我没有把孤儿带走,也没有培养他们。如果要删除某些子对象,请按以下方式执行:
//This line attaches a parent object to the session. EF will start monitoring it.
Entry(parent).State = EntityState.Modified;
//This code is responsible for finding children to delete.
foreach (var child in parent.Children.Where(ch => ch.Deleted))
//This line says EF that given child should be removed.
//This line also causes that an object will be removed from Children collection.
Entry(child).State = EntityState.Deleted;
SaveChanges();
Deleted是一个属性,如果要删除对象,我会将其设置为true
modelBuilder.Entity<Child>().HasKey(x => new { x.ChildId, x.Parent });
//This line attaches a parent object to the session. EF will start monitoring it.
Entry(parent).State = EntityState.Modified;
//This code is responsible for finding children to delete.
foreach (var child in parent.Children.Where(ch => ch.Deleted))
//This line says EF that given child should be removed.
//This line also causes that an object will be removed from Children collection.
Entry(child).State = EntityState.Deleted;
SaveChanges();