Entity Framework - Clear a Child Collection

前端 未结 3 1027
走了就别回头了
走了就别回头了 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: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.

提交回复
热议问题