使用过滤器清除相关表属性

时间:2020-05-26 12:31:48

标签: c# entity-framework-6

我有一个名为Parent的表,它与一个名为Child的表具有多对多关系。在EF模型中,Parent是具有类型为Child的称为ICollection<Child>的属性的实体。

我可以在程序中这样做,以删除所有相关的Child元素,然后重新填充它:

Parent entity = context.Parent.FirstOrDefault(someCondition);
entity.Child.Clear();  // remove all related child elements (in database, only data in the associated table is removed)
entity.Child.Add(newChildEntity)
context.SaveChanges();

但是,如果我需要使用条件删除Child元素怎么办?

我尝试过:

entity.Child.Where(otherCondition).Clear();

但是由于Where方法返回了IEnumerable<Child>,所以我不能使用Clear()方法。

另一种尝试是在调用ICollection<Child>方法之前将其强制转换为Clear,但是引发了异常,提示无法进行强制转换。

有什么帮助吗?

也许我可以得到entity.Child.Where(otherCondition)然后使用ForEach循环来Remove所有元素,但是,除了提供非常差的性能外,我认为Child元素也是不仅删除了关系数据。

Jaime

2 个答案:

答案 0 :(得分:0)

Where方法返回一个IEnumerable<Child>,您可以将其转换为列表。

您尝试将IEnumerable转换为列表并清除列表吗?像这样:

List<Child> mylist= enumerable.ToList(); 
mylist.Clear();

答案 1 :(得分:-1)

如果您的dbContext不是这样,那么我认为您应该重组数据库以提高效率。

public MyDbContext
{
   //Details obscured for brevity
   public DbSet<Parent> Parents {get; set; }
   public DbSet<Child> Children {get; set;}
}
//Your models
public class Parent
{
   public string Id {get; set;}
   //......
}
public class Child
{
   public string Id {get; set;}
   //If a child can have just one parent
   public string ParentId {get; set;}
   //......

   public virtual Parent Parent {get; set;}
}
//Another table if a child can have more than one parent
public class ParentChild
{
   public string ParentId {get; set;}
   public string ChildId {get; set;}
   //......
   public virtual ICollection<Parent> Parents {get; set;}
   public virtual ICollection<Child> Children {get; set;}
}

那么你可以

context.DbSet<Child>().Remove(x => x.ParentId == myParentId);

OR

context.DbSet<ParentChildren>().Remove(x => x.ParentId == myParentId);