Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper method for deleting entity in one-to-many relationship

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; }
}
like image 549
Brock Noland Avatar asked Aug 31 '13 16:08

Brock Noland


People also ask

How do you remove an entity from a one to many relationship?

If an entity that is the target of the relationship is removed from the relationship (by setting the relationship to null or removing the entity from the relationship collection), the remove operation will be applied to the entity being orphaned. The remove operation is applied at the time of the flush operation.

What is CascadeType remove?

CascadeType. REMOVE : It means that the related entities are deleted when the owning entity is deleted. CascadeType. DETACH : It detaches all the related entities if a manual detach occurs.


1 Answers

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.

like image 54
Brock Noland Avatar answered Sep 28 '22 03:09

Brock Noland