我有一个这样的数据库结构。每个员工都属于一个部门,每个股票都属于一个部门,每个部门都有一个员工列表和与之关联的股票列表。我使用以下代码初始化数据库:
$data.define("Org.Department",{
ID: {key: true, type: "integer", computed: true},
DepartmentID: {type: "integer", required: true},
DepartmentName: {type: "string", required: true},
Employee:{type: Array, elementType: "Org.Employee", navigationProperty:"Department"},
Stock:{type: Array, elementType: "Org.Stock", navigationProperty:"Department"}
});
$data.define("Org.Employee",{
ID: {key: true, type: "integer", computed: true},
Name: {type: "string", required: true},
DepartmentID: {type: "integer", required: true},
Department: {type: "Org.Department", inverseProperty: "Employee"}
});
$data.define("Org.Stock",{
ID: {key: true, type: "integer", computed: true},
DepartmentID: {type: "integer", required: true},
Description: {type: "string"},
NumItems: {type: "integer", 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,
dbCreation: $data.storageProviders.DbCreationType.DropAllExistingTables
});
我想做的是向该数据库添加元素,但我必须建立正确的连接。我的意思是正确的连接,我想查询所有员工的姓名,这需要我查找部门名称并从中获取员工列表,然后列出他们的姓名。我尝试了很多东西,但完全失败了。例如:
x.onReady(function(){
var dep;
x.Departments.filter(function(res){
return res.DepartmentID==4;
}).forEach(function(it){
dep=it;
});
console.log(dep);
var emp=new Org.Employee({
Name: 'Employee1',
DepartmentID: 4,
Department:dep
});
x.Employees.add(emp);
x.Employees.saveChanges();
});
未能在员工内部插入正确的部门信息。当我查询 Employee1 的部门字段时,我得到未定义。
这也失败了:
x.Employees.add({Name:"Employee1",DepartmentID:4});
所有查询都成功地将一些数据插入到数据库中,但它们的部门字段为空,这违背了拥有关系数据库的全部目的。