Search code examples
c#knockout.jsbreezeone-to-manyhottowel

breezejs- how to add a new child entity and attach it to parent's collection of children


I have a model with navigation property from database. The structure of the model is as follows

public class Parent{
  public string propertyone {get; set;}
  public IList<Child> children {get; set;}
}

public class Child{ 
  public string propertyone {get; set;}
  public string propertytwo {get; set;}
  public IList<Seed> children {get; set;}
}

Using breeze, I load a single object of type 'Parent' from the database and display the "children" property in a table.

this.parent= manager.fetchEntityByKey('Parent', 42)

On click of a button, I want to add another child

<table data-bind="with: parent">
       <tr data-bind="foreach: children">
          <td data-bind="text: children"></td>
          <td data-bind="text: children"></td>
          <td><a data-bind="click: $root.remove">Remove</a></td>
       </tr>
 </table>
 <a data-bind="click: $root.add">Add</a>

My add function which does not work looks like this, where self represents the returned view model.

function add(parent){
  var newchild= ko.observable(entityType.createEntity(
                        {
                            propertyone : "Test"

                        }));
  parent.children.push(newchild);
  //parent().children().push(newchild);
  //self.parent.children.push(newchild);
  //self.parent().children().push(newchild);
}

This as well as the commented lines in the add function is what I have tried but that does not work. I receive the error, undefined is not a function. How Do i add an item to this navigation collection representing the one to many relationship between the parent and children entities?


Solution

  • Provided your metadata is setup correctly all you need is:

    entityType.createEntity({ parentIdProperty: 'parent id value' });
    

    This will create the entity and add it to the parent entity's collection.