Search code examples
asp.net-web-apiodata

$select on navigation property / WebApi 2.0 / OData 4


Given the following simple OData 4 controller (please see below), how do I $select just the cities?

http://localhost//api/Customers?$select=Location

Gives me:

{
  "@odata.context":"http://localhost/api/$metadata#Customers(Location)","value":[
    {
      "Location":{
        "Country":"Ireland","City":"Sligo"
      }
    },{
      "Location":{
        "Country":"Finland","City":"Helsinki"
      }
    }
  ]
}

But I don't know how to drill down one deeper so that I just get the cities. Is this even possible?

public class CustomersController : ODataController
{
    private List<Customer> customers = new List<Customer>()
    {
        new Customer
        {
            CustomerId = 1,
            Location = new Address
            {
                City = "Sligo",
                Country = "Ireland"
            }
        },
        new Customer
        {
            CustomerId = 2,
            Location = new Address
            {
                City = "Helsinki",
                Country = "Finland"
            }
        }
    };

    [EnableQuery]
    public List<Customer> Get()
    {
        return customers;
    }
}

Solution

  • The grammar for $select does not allow a path expression like Location/City. Your best bet is to define an OData function bound to the Customers entity set. E.g.,

    [HttpGet]
    public IEnumerable<string> GetCities()
    {
        return customers.Select(c => c.Location.City);
    }
    

    And invoke it as follows:

    GET http://localhost/api/Customers/ServiceNamespace.GetCities