7

我有亲子关系(一对多)。我能够创建孩子,但删除失败。我创建了一个孩子,保存它,但是当我删除时,我得到:

A foreign key value cannot be inserted because a corresponding primary key value 
does not exist. [ Foreign key constraint name = FK_dbo.Children_dbo.Parents_ParentId ]

我确实注意到,当删除被发送到服务器时,孩子的 parentid 为 0,实体状态为“已修改”。我希望这会被“删除”。

相关视图模型部分:

function queryFailed(error) {
  console.log('Query failed: ' + error.message);
}
function save() {
  dataservice.saveChanges().fail(queryFailed);
}
function deleteChild(child) {
  parent().children.remove(child);
}
function addChild() {
  dataservice.createChild(parent);
}

HTML:

<section data-bind="with: parent">
  <div data-bind="foreach: children">
    <div>
      <select name="propertyOne" 
        data-bind="options: propertyOneOptions, value: propertyOne, optionsText: 'description', optionsCaption: 'Select a Property'">
      </select>
      <button data-bind="click: $root.deleteChild">Delete Child</button>
    </div>
  </div>
  <button data-bind="click: $root.addChild">Add Child</button>
</section>
<button data-bind="click: save">Save</button>

数据模型:

public class Parent
{
  public Parent()
  {
    Children = new List<Child>();
  }
  [Key]
  public int Id { get; set; }

  public String OtherProperty { get; set; }

  public IList<Child> Children { get; set; }

}
public class Child
{
  [Key]
  public int Id { get; set; }

  public int ParentId { get; set; }

  [ForeignKey("ParentId")]
  public Parent Parent { get; set; }
}
4

1 回答 1

8

事实上,我没有正确删除实体。我应该:

child.entityAspect.setDeleted();

我以为我已经正确阅读了更改跟踪文档,但实际上我没有。

于 2013-09-01T16:57:38.757 回答