无法使用SelectMany在DocumentDb LINQ查询中获取父属性

时间:2017-08-07 13:54:00

标签: linq linq-to-sql azure-cosmosdb

我有一个嵌套的文档结构,如:

[
  {
    "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"
  },
 ...
]

我使用SelectMany子句在LINQ中编写了一个类似的查询,如下所示,但它会抛出一个错误,说明SelectMany只能有2个参数。

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

1 个答案:

答案 0 :(得分:2)

你需要用嵌套的Select“推”第一个lambda中的第二个lambda,如下所示:

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