2013-10-02 40 views
1

我想用自定义的JsonResultsAdapter连接到使用Breeze的第三方服务。JsonResultsAdapter中的嵌套实体

第三方服务具有与数组根节点中的实体相关的“元数据”,则这些变量位于“元数据”对象的“数据”属性中。

该格式有两种定义关系的方式。一个是通过引用另一个实体的id的“@ref”字段。另一种是通过内联定义相关对象(而不是“@ref”),该对象没有明确的id,但只有“parent”对象才引用该对象。

的数据看起来像:

[{ 
    "id" : "abc", 
    "type" : "foo", 
    "data": { "relationshipRef" : { "@ref" : "someid" } } 
}, 
{ 
    "id": "someid", 
    "type" : "bar", 
    "data" : { "relationshipInline" : { "type" : "baz", 
             "data" : { "something" : "whatever", 
                "innerRelation" : { "@ref" : "abc"} 
               } 
      } 
    }] 

我目前(在JsonResultsAdapter的visitNode功能)中的“数据”移动对象的属性成“根”节点,然后用更换任何对象“@ref”属性与“@ref”键的值并将一个ID附加到末尾(以便关系可以使用EntityType中的原始名称)。 IE,第一个对象将变成:

{ 
    "id" : "abc", 
    "type" : "foo", 
    "relationshipRefID" : "someid" 
} 

这适用于顶级实体和关系,但我遇到了嵌套问题。

你会如何解决这个问题?

我打算使用ComplexTypes,但文档提到它们不能具有“navigationProperties”(关系),正如您在上面看到的那样,它是必需的(“innerRelation”属性)。

在某些情况下,实体可以嵌套到3层左右。

这是我目前的visitNode功能:

 visitNode: function(node, parseContext, nodeContext) { 
      if(node instanceof Object && node.type != null) { 
       if(node.deleted) { 
        //TODO: make sure the object is removed from the manager 
        return {ignore:true}; 
       } 

       //We need to tweak the data structure to fit what breeze expects. 
       //It expects properties to be in the same level as the "metadata" for an object ("type" etc), 
       //So we need to move the properties from the data object into the node, and fix up relationships. 
       if(parseContext.entityManager.metadataStore.getEntityType(node.type, true) != null) { 

        var data = node.data; 
        for(var key in data) { 

         var prop = data[key]; 
         //Move any foreign key fields to be "relationID":id instead of "relation":{"@ref":id} 
         if(prop instanceof Object) { 
          var ref = prop["@ref"]; 
          if(ref != null) { 
           node[key+"ID"] = ref 
           data[key] = null; 
           continue; 
          } 
         } 
         //TODO: Handle inline references <- This is where I need help! 

         node[key] = data[key]; 
        } 

        return { 
         entityType: node.type, 
         nodeId: node.id 
        } 
       } 
       else { 
        return {ignore:true}; 
       } 
      } 
     } 

回答

1

嗯,显然我应该已经测试了询问这里之前。

事实证明,这可以根据模型中定义的navigationProperties自动工作!真棒。我确实必须为没有它们的内部节点生成id,但这很简单。

+0

感谢发表回复:) –