【问题标题】:How can I filter by nested properties in OData?如何按 OData 中的嵌套属性进行筛选?
【发布时间】:2014-01-18 11:50:23
【问题描述】:

我将 OData 与 Web API 一起使用以返回以下 JSON:

[
{
    "EmployeeID": 1,
    "FirstName": "Nancy",
    "LastName": "Davolio",
    "Title": "Sales Representative",
    "HireDate": "\/Date(704649600000)\/",
    "Territories": [
        {
            "TerritoryID": "06897",
            "TerritoryDescription": "Wilton"
        },
        {
            "TerritoryID": "19713",
            "TerritoryDescription": "Neward"
        }
    ]
}
]

例如,我如何过滤 JSON 以显示属于 Wilton 领域的项目? 我已经尝试过了,但似乎不起作用:

http://localhost:62559/Home/Read?$filter=Territories/TerritoryDescription eq Wilton

这是我用来使用存储库模式从数据库返回对象的代码:

[Queryable]
public IQueryable<EmployeeViewModel> Employees
{
  get
  {
    return context.Employees.Select(e => new EmployeeViewModel
    {
        EmployeeID = e.EmployeeID,
        FirstName = e.FirstName,
        LastName = e.LastName,
        HireDate = e.HireDate,
        Title = e.Title,
        Territories = e.Territories.Select(t => new TerritoryViewModel
        {
            TerritoryID = t.TerritoryID,
            TerritoryDescription = t.TerritoryDescription
        })
    });
  }
}

这是以 JSON 格式返回对象的控制器:

public ActionResult Read()
{
    return Json(repository.Employees, JsonRequestBehavior.AllowGet);
}

【问题讨论】:

    标签: c# json asp.net-web-api odata


    【解决方案1】:

    假设您有一个这样的嵌套 JSON 数组对象,并且必须在下面的击球手/顶部键上应用 Odata 过滤器,那么您必须使用 / 来引用键。 p>

    例如,您必须选择击球手 id - 语法为 过滤器:batters/id eq '1001' ;击球手/类型 ne '巧克力'

    {
    "id": "0001",
    "type": "Cook Cake",
    "name": "Customized",
    "batters":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food" }
                ],
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
        ]
    }
    

    【讨论】:

      【解决方案2】:

      在阅读与我相关的问题时,我遇到了以下答案:
      Nested filter on Data Transfer Object using OData Wep Api

      有趣的是,我在之前对 SO 的搜索中从未遇到过这个问题。不然我就不用问这个问题了。无论如何,这种方法对我有用:

      http://localhost:62559/Home/Read?$filter=Territories/any(c:%20c/TerritoryDescription eq 'Wilton')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-01
        • 2019-03-22
        • 1970-01-01
        • 2013-09-25
        • 1970-01-01
        • 1970-01-01
        • 2016-02-15
        相关资源
        最近更新 更多