简体   繁体   中英

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?

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.

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

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

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM