Remove all child objects

child-objects entity-framework

Question

I'm attempting to update the following resource:

  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

With one exception: I do not delete the Restrictions, I am working on something similar to build a resource.

The following error is appearing for me:

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 overlooking?

1
1
7/16/2015 12:28:13 PM

Accepted Answer

EF carried out your instructions to the letter. Removing an item from the navigation collection for parent objects merely ends the relationship between the parent and child objects. This signifies that your entity model forbids doing anything else than setting ResourceId in Restriction to null.

You should represent the connection as identifying whether your restriction cannot exist without the connected resource. It implies that the ResourceId column will also be part of the Restriction main key. EF will destroy the restriction when the restriction is later removed from the parent object collection rather than setting the ResourceId to null.

11
1/17/2011 12:13:15 PM

Popular Answer

Similar issues plagued me since the opposite of Add() certainly seemed to be Remove ().

To remove child objects, you must use the DeleteObject() method.

Thanks.



Related Questions





Related

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