2017-08-07 17 views
2

我有一個嵌套的文件結構,如:無法使用的SelectMany在DocumentDb LINQ查詢來獲取parent屬性

[ 
    { 
    "id": "parent1", 
    "children": [ 
     { 
     "id": "child1", 
     "foo": "bar" 
     }, 
     { 
     "id": "child2", 
     "foo": "bar" 
     }, 
     { 
     "id": "child3", 
     "foo": "bar" 
     } 
    ] 
    }, 
    { 
    "id": "parent2", 
    "children": [ 
     { 
     "id": "child4", 
     "foo": "bar" 
     }, 
     { 
     "id": "child5", 
     "foo": "bar" 
     } 
    ] 
    } 
] 

我能寫SQL語法以下查詢:

SELECT child, parent.id 
FROM parent 
JOIN child in parent.children 

這得到我以下結果:

[ 
    { 
    "child": { 
     "id": "child1", 
     "foo": "bar" 
    }, 
    "id": "parent1" 
    }, 
... 
] 

我寫了一個類似的查詢在LINQ使用SelectMany子句如下s,但它會引發一個錯誤,說明SelectMany只能有2個參數。

collection.SelectMany(
    parent => parent.children, 
    (parent, child) => new { child, parent.id }); 
+0

您的查詢看起來很確定我。它是不是理解這個「SelectMany」超載的O-R映射器?確切的錯誤信息?如果是,dasblinkenlight的答案可以解決它。 – tinudu

回答

1

你需要「推動」第二半波的第一半波帶內嵌套Select,像這樣:

collection.SelectMany(
    parent => parent.children.Select(child => new { 
     Child = child 
    , ParentId = parent.id 
    }) 
);