我的单页应用程序中有一个 Breeze 数据服务(又名 datacontext)。我想从 WebAPI 控制器获取运行列表以及每次运行的 OutlineItems 列表。
控制器使用 BreezeController 上的此方法返回带有子 OutlineItems 的打开运行列表。
[AcceptVerbs("GET")]
public IQueryable<Run> Runs()
{
return _contextProvider.Context.Runs
.Include("RunOutlineItems")
.AsQueryable()
.Where(r => r.RunStatusId < 4); // 4 is the cutoff for open items
}
这是数据模型。
namespace PilotPlantBreeze
{
public class Run
{
public int Id { get; set; }
public string Name { get; set; }
public string Rundate { get; set; }
public DateTime? RunStart { get; set; }
public int MachineId { get; set; }
public int ProductId { get; set; }
public int RunStatusId { get; set; }
public string Comments { get; set; }
// Nav props
public IList<OutlineItem> RunOutlineItems { get; set; }
}
}
当我查看来自 WebAPI 请求的响应数据时,RunOutlineItems 列表位于 JSON 中。这里以一项为例:
{
"$id":"27",
"$type":"PilotPlantBreeze.OutlineItem,PilotPlantBreeze.Model",
"Id":22,
"RunId":5,
"TankId":4,
"OutlineTopicId":1,
"OutlineDescriptionId":9,
"PersonId":1,
"Value":"23"
}
这是我从 WebAPI 获取数据的客户端 JavaScript 代码。为清楚起见,省略了错误检查和本地缓存检查。
var getRuns = function () {
// The EntityQuery is defined at the beginning of the dataservice
// Here I am asking for a query on the server. Note the .expand
// which is supposed to avoid lazy loading. Lazy loading is turned off
// on the WebAPI already.
var query = EntityQuery
.from("Runs")
.expand("RunOutlineItems")
.orderBy("rundate");
// The manager is defined at the beginning of the dataservice
// Here I am asking the manager to execute the query with a promise
return manager.executeQuery(query)
.then(runsQuerySucceeded)
.fail(runsQueryFailed);
// The promise does not fail, but I would put an error in here if it ever does
function runsQueryFailed(data) {
}
// When the promise succeeds, the data parameter is the JSON from the WebAPI
function runsQuerySucceeded(data) {
//
// When I stop the debugger here data.results holds the entities, but
// the child entities for the RunOutlineItems is an observableArray with
// nothing in it.
//
app.vm.runs.runs(data.results);
}
};
所以我的问题是如何将子项放入我的视图模型中。我有一个解决方法,它在服务器上对 WebAPI 的单独调用中获取子项,并使用自定义 ko.bindHandler 处理它们,但是让导航技术工作会很方便。