EntityCollection Clear() and Remove() methods

前端 未结 5 1982
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 04:53

What is the right way to delete all of the collection items of an EF entity? In the code below, DocumentItems is the collection of related document items for a document. Thi

5条回答
  •  长发绾君心
    2021-01-04 05:58

    Trick: When setting up the relationship between Parent and Child, you'll HAVE TO create a "composite" key on the child. This way, when you tell the Parent to delete 1 or all of its children, the related records will actually be deleted from the database.

    To configure composite key using Fluent API:

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

    Then, to delete the related children:

    var parent = _context.Parents.SingleOrDefault(p => p.ParentId == parentId);
    
    var childToRemove = parent.Children.First(); // Change the logic 
    parent.Children.Remove(childToRemove);
    
    // or, you can delete all children 
    // parent.Children.Clear();
    
    _context.SaveChanges();
    

    Done!

提交回复
热议问题