Entity Framework - Clear a Child Collection

前端 未结 3 1028
走了就别回头了
走了就别回头了 2020-12-15 17:26

I have run into an interesting problem with Entity Framework and based on the code I had to use to tackle it I suspect my solution is less than ideal. I have a 1-to-Many rel

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 18:03

    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);
    
    // you can delete all children if you want 
    // parent.Children.Clear();
    
    _context.SaveChanges();
    

    Done!

提交回复
热议问题