Entity Framework - Clear a Child Collection

前端 未结 3 1026
走了就别回头了
走了就别回头了 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<Child>().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!

    0 讨论(0)
  • 2020-12-15 18:16

    Clear() removes the reference to the entity, not the entity itself.

    If you intend this to be always the same operation, you could handle AssociationChanged:

    Entity.Children.AssociationChanged += 
        new CollectionChangeEventHandler(EntityChildrenChanged);
    Entity.Children.Clear();            
    
        private void EntityChildrenChanged(object sender,
            CollectionChangeEventArgs e)
        {
            // Check for a related reference being removed. 
            if (e.Action == CollectionChangeAction.Remove)
            {
                Context.DeleteObject(e.Element);
            }
        }
    

    You can build this in to your entity using a partial class.

    0 讨论(0)
  • 2020-12-15 18:18

    You can create Identifying relationship between parent and child entities and EF will delete child entity when you delete it from parent's collection.

        public class Parent
        {
          public int ParentId {get;set;}
          public ICollection<Child> Children {get;set;}
        }
    
        public class Child
        {          
          public int ChildId {get;set;}
          public int ParentId {get;set;}
        }
    

    Mapping configuration:

        modelBuilder.Entity<Child>().HasKey(x => new { x.ChildId, x.ParentId });
        modelBuilder.Entity<Parent>().HasMany(x => x.Children).WithRequired().HasForeignKey(x => x.ParentId);
    
    0 讨论(0)
提交回复
热议问题