简体   繁体   English

删除子对象

[英]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. “ Restrictions_ResourceId_FK” AssociationSet中的关系处于“已删除”状态。 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. EF完全按照您的要求去做。 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. 这意味着它仅将Restriction中的ResourceId设置为null,这是您的实体模型不允许的。

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. 这意味着限制主键还将包含ResourceId列。 When you then remove restriction from parent object collection, EF will delete restriction instead of setting ResourceId to null. 当您从父对象集合中删除限制时,EF将删除限制,而不是将ResourceId设置为null。

I was having similar problems since the opposite of Add() obviously seemed Remove(). 我遇到了类似的问题,因为Add()的反面似乎是Remove()。

You must use the DeleteObject() function instead to delete child items. 您必须使用DeleteObject()函数来删除子项。

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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