如何在OData中按嵌套属性进行过滤?

时间:2013-12-31 14:58:13

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

我正在将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以显示属于威尔顿地区的项目? 我试过这个,但似乎不起作用:

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);
}

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:0)

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

>

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

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