Clear a Child Collection in Entity Framework



Entity Framework has presented me with an intriguing dilemma, and judging by the code I had to use to solve it, I don't think my answer is the best. Table A and Table B have a 1-to-Many connection in which entities in Table B refer to Table A. I want to concurrently erase every row's children in TableA, and I believed I could do this by just deleting the collection:


Unfortunately, this resulted in a Foreign Key violation when I tried to save adjustments.

A relationship is being added or deleted from an AssociationSet 'FK_EntityB_EntityA'. With cardinality constraints, a corresponding 'EntityB' must also be added or deleted.

I found a workaround by manually deleting objects using the entity context's DeleteObject() function, but I simply know that my thinking is flawed.

while (collection.Any())

One thing that seems far from ideal is the fact that I had to use a Where() loop, but I assume that's just a semantic judgment on my side. Anyhow, is there a problem with the way I'm going about this, or is there potentially a better method to delete all the deleted objects from a child entity collection of an entity so that Entity Framework correctly executes a data store delete on them all?

1/13/2010 6:22:50 PM

Accepted Answer

Clear() removes the entity's reference, not the entity itself.

You could manage this if you intended for it to be the same procedure.AssociationChanged :

Entity.Children.AssociationChanged += 
    new CollectionChangeEventHandler(EntityChildrenChanged);

    private void EntityChildrenChanged(object sender,
        CollectionChangeEventArgs e)
        // Check for a related reference being removed. 
        if (e.Action == CollectionChangeAction.Remove)

You may include this using a partial class in your business.

1/13/2010 5:22:34 PM

Popular Answer

When an entity is deleted from the parent's collection, EF will destroy the child entity if there is an Identifying connection between the two.

    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;}

Configuration for mapping:

    modelBuilder.Entity<Child>().HasKey(x => new { x.ChildId, x.ParentId });
    modelBuilder.Entity<Parent>().HasMany(x => x.Children).WithRequired().HasForeignKey(x => x.ParentId);

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow