【问题标题】:Delete child objects删除子对象
【发布时间】:2011-01-16 21:04:39
【问题描述】:

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

  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

我有类似的东西,并且正在努力创建一个只有一个区别的资源:我没有删除限制。

我收到以下错误:

一种关系 'Restrictions_ResourceId_FK' AssociationSet 在“已删除”中 状态。给定多重约束, 必须有相应的“限制” 也处于“已删除”状态。

我错过了什么?

【问题讨论】:

    标签: entity-framework child-objects


    【解决方案1】:

    EF 完全按照您告诉他的去做。从父对象导航集合中删除项目只会删除父对象和子对象之间的关系。这意味着它只将 Restriction 中的 ResourceId 设置为 null,这是您的实体模型所不允许的。

    如果您的限制在没有相关资源的情况下无法存在,您应该将关系建模为识别。这意味着 Restriction 主键也将包含 ResourceId 列。当您随后从父对象集合中删除限制时,EF 将删除限制而不是将 ResourceId 设置为 null。

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题,因为 Add() 的反面显然是 Remove()。

      您必须改用 DeleteObject() 函数来删除子项。

      谢谢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-25
        • 2021-07-23
        • 2018-07-30
        • 2019-05-12
        • 1970-01-01
        • 1970-01-01
        • 2018-12-27
        • 1970-01-01
        相关资源
        最近更新 更多