【问题标题】:$select on navigation property / WebApi 2.0 / OData 4$select 导航属性/WebApi 2.0/OData 4
【发布时间】:2016-05-20 23:49:04
【问题描述】:

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

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

【问题讨论】:

    标签: asp.net-web-api odata


    【解决方案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
    

    【讨论】:

    • 谢谢,我最后就是这么做的。
    猜你喜欢
    • 2013-06-27
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多