Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I filter by nested properties in OData?

I'm using OData together with Web API to return the following JSON:

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

How can I filter the JSON to display items that belong to the Wilton territory, for example? I've tried this but doesn't seem to work:

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

This is the code I'm using to return objects from the database using a repository pattern:

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

Here is the controller that returns objects in JSON:

public ActionResult Read()
{
    return Json(repository.Employees, JsonRequestBehavior.AllowGet);
}
like image 425
nouptime Avatar asked Dec 31 '13 14:12

nouptime


Video Answer


1 Answers

I came across the following answer while reading up on questions related to mine:
Nested filter on Data Transfer Object using OData Wep Api

Funny thing is, I never came across that question in my previous searches on SO. Otherwise I wouldn't have to ask this question. Anyway this method works for me:

http://localhost:62559/Home/Read?$filter=Territories/any(c:%20c/TerritoryDescription eq 'Wilton')
like image 197
nouptime Avatar answered Sep 29 '22 18:09

nouptime