导航属性上的$ select / WebApi 2.0 / OData 4

时间:2016-05-20 14:20:51

标签: asp.net-web-api odata

鉴于以下简单的OData 4控制器(请参见下文),我如何选择只是城市?

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

给我:

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

但是我不知道如何更深入地向下挖掘,以便我能够获得城市。这甚至可能吗?

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

1 个答案:

答案 0 :(得分:1)

$select的语法不允许使用Location/City这样的路径表达式。最好的办法是定义一个绑定到Customers实体集的OData函数。如,

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

并按如下方式调用它:

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