删除子对象 [英] Delete child objects

查看:144
本文介绍了删除子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新资源如下:

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.

我收到以下错误:


'Restrictions_ResourceId_FK'
的关系AssociationSet处于'Deleted'
状态。给定多重约束,
a对应的限制也必须在已删除状态下

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.

什么是我缺少?

推荐答案

EF完全符合你所说的要求。从父对象导航集合中删除项目仅删除父对象和子对象之间的关系。这意味着它只将Restrict中的ResourceId设置为null,这不允许您的实体模型。

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.

如果您的限制不存在没有相关资源,您应该将关系建立为识别。这意味着Restriction主键还将包含ResourceId列。当您从父对象集合中删除限制时,EF将删除限制,而不是将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. When you then remove restriction from parent object collection, EF will delete restriction instead of setting ResourceId to null.

这篇关于删除子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆