entity-frameworkchild-objects

Delete child objects


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?


Solution

  • 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.