I fixed two important things in the code and now it's working:
- navigationProperty should be inverseProperty. You always have to define the other side of the relationship with inverseProperty - please share the URL where you had found this navigationProperty, I check if I can fix it
if you read an item from the DB and set it in a relationship, you have to attach the item to the context
$data.define("Org.Department",{ ID: {key: true, type: "int", computed: true}, DepartmentID: {type: "int", required: true}, DepartmentName: {type: "string", required: true}, Employee:{type: Array, elementType: "Org.Employee", inverseProperty: "Department"}, Stock:{type: Array, elementType: "Org.Stock", inverseProperty: "Department"} });
The fixed code:
$data.define("Org.Employee",{
ID: {key: true, type: "int", computed: true},
Name: {type: "string", required: true},
DepartmentID: {type: "int", required: true},
Department: {type: "Org.Department", inverseProperty: "Employee"}
});
$data.define("Org.Stock",{
ID: {key: true, type: "int", computed: true},
DepartmentID: {type: "int", required: true},
Description: {type: "string"},
NumItems: {type: "int", required: true},
Department: {type: "Org.Department", inverseProperty: "Stock"}
});
$data.EntityContext.extend("Company",{
Employees: {type: $data.EntitySet, elementType: Org.Employee},
Departments: {type: $data.EntitySet, elementType: Org.Department},
Stocks: {type: $data.EntitySet, elementType: Org.Stock}
});
var x= new Company({
provider: "webSql",
databaseName: "DB",
version: 1
});
x.onReady(function(){
var newDep = new x.Departments.elementType({DepartmentName: 'dep1', DepartmentID: 7});
x.Departments.add(newDep);
x.saveChanges(function() {
x.Departments.first("it.DepartmentName == 'dep1'", {}, function(dep){
console.log(dep);
x.Departments.attach(dep);
var emp = new Org.Employee({
Name: 'Employee1',
DepartmentID: dep.DepartmentID,
Department:dep
});
console.log(emp);
x.Employees.add(emp);
x.Employees.saveChanges();
});
})
});
You can find a the live version on jsfiddle