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; }
}