Proper method for deleting entity in one-to-many relationship
Asked Answered
K

1

7

I have a parent-child relationship (one-to-many). I am able to create children but the delete fails. I create a child, save it, but when I delete I get:

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 ]

I did notice that when the delete is sent to the server, the child has a parentid of 0 and entity state of "modified". I would expect this to be "deleted".

Relevant View Model portions:

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>

Data Model:

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; }
}
Kingcraft answered 31/8, 2013 at 16:55 Comment(0)
K
8

Indeed I was not deleting the entity correctly. I should have:

child.entityAspect.setDeleted();

I thought I had read the change tracking document correctly but in fact I had not.

Kingcraft answered 1/9, 2013 at 16:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.