Remove all child objects

child-objects entity-framework


I am trying to update a resource as follows:

  public void Update(Resource resource) {

   Resource _resource = _resourceRepository.First(r => r.Id == resource.Id);

   _resource.Content = resource.Content;
   _resource.Description = resource.Description;
   _resource.Locked = resource.Locked;
   _resource.Name = resource.Name;

   _resource.Restrictions.ToList().ForEach(r => _resource.Restrictions.Remove(r));

   foreach (Restriction restriction in resource.Restrictions)
    _resource.Restrictions.Add(new Restriction { Property = _propertyRepository.First(p => p.Id == restriction.Property.Id), Value = restriction.Value });

  } // Update

I have something similar, and working, to create a resource with only one difference: I do not remove the Restrictions.

I am getting the following error:

A relationship from the 'Restrictions_ResourceId_FK' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Restrictions' must also in the 'Deleted' state.

What am I missing?

7/16/2015 12:28:13 PM

Accepted Answer

EF did exactly what you told him to do. Removing item from parent object navigation collection only removes relation between parent and child object. It means it only sets ResourceId in Restriction to null which is not allowed by your entity model.

If your Restriction can't exist without related resource you should model relation as Identifying. It means that Restriction primary key will also contain ResourceId column. When you then remove restriction from parent object collection, EF will delete restriction instead of setting ResourceId to null.

1/17/2011 12:13:15 PM

Popular Answer

I was having similar problems since the opposite of Add() obviously seemed Remove().

You must use the DeleteObject() function instead to delete child items.


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