【问题标题】:OData: Could not find a property named on inherited typeOData:找不到以继承类型命名的属性
【发布时间】:2015-01-09 15:02:07
【问题描述】:

例如,我有两个类

public class Location
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string CountryCode { get; set; }
}

public class Customer : Location
{
    public string BankAccountNumber { get; set; }
    public string BankSortCode { get; set; }
}

在我的查询中,我返回了所有位置和客户。

http://localhost:80/odata/Location?select=Id,Name,Town

但是,如果我尝试在客户中选择任何内容(编辑:所以我想要所有位置,但如果该位置也是客户,则需要银行帐号),我会收到错误消息。

http://localhost:80/odata/Location?select=Id,Name,Town,BankAccountNumber

"The query specified in the URI is not valid. Could not find a property named 'BankAccountNumber' on type 'MyNamespace.Location'."

有什么方法可以选择继承类型中的字段,而不选择全部?谢谢。

【问题讨论】:

  • 您能否向我们展示一下您是如何在 webapi 配置中配置 OData 端点以及您的 Dbcontext 的样子?也许我们可以在那里找到一些东西

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


【解决方案1】:

根据OData.org,查询派生类型有2个选项:

  1. ~/Location!Customer/
  2. ~/Location/OfType('Customer')

所以你的查询应该是这样的:

http://localhost:80/odata/Location!Customer?select=Id,Name,Town,BankAccountNumber

http://localhost:80/odata/Location/OfType('Customer')?select=Id,Name,Town,BankAccountNumber

/编辑: 钱立指出,以上博文指的是OData V2。在 Odata4 中,继承类型按以下语法访问:

http://host/service/BaseType/Model.SubType

参考:http://docs.oasis-open.org/odata/odata/v4.0/os/part2-url-conventions/odata-v4.0-os-part2-url-conventions.html#_Toc372793786

【讨论】:

  • 它在文档中,但 Web Api 似乎没有实现这个。这两种方法都出现 404 错误。 :(
  • 您是否将客户定义为实体类型?如果是这样,请尝试调用 /Customer/?select ... 而不是 /Location?select...
  • @Serv 您提到的博客是针对 OData V2 的,并且不能很好地支持继承。而那个博客中的OfType 实际上是一个自定义操作,这就是它无法工作的原因。
  • @QianLi。对,错过了。
  • 将此作为解决我的问题的参考发布:确保您对该属性的访问修饰符设置为公共。就我而言,我有public string Something { get; protected set; }
【解决方案2】:

您不仅应该添加类型名称,还应该添加类型的命名空间。 例如: http://services.odata.org/TripPinWebApiService/People('russellwhyte')/Trips(1001)/PlanItems/ODataSamples.WebApiService.Models.Flight?$select=StartsAt

Flight 类型继承自 PlanItem 类型。 ODataSamples.WebApiService.Models 是命名空间。

派生类型的更多详细信息,如果您发现spec 太长无法阅读,您可以参考http://www.odata.org/getting-started/advanced-tutorial/ 并提供一些实例...

【讨论】:

  • 谢谢。它似乎确实排除了不是航班的 PlanItems。不能在查询中包含非航班项目吗?在这种情况下,我的问题是获取所有项目的 StartAt 和 SeatNumber(但 SeatNumber 在事件中将为空/缺失)。
  • 我现在明白你的问题了。我不确定,但我认为这样的请求不能直接通过 OData 请求获得。 1) 在我看来,基于基类型同时请求基属性和派生属性似乎不是一个好的模型。更清楚地说,如果在../BaseType/$select=A,B 中请求属性A 和B,那么AB 应该都在BaseType 中。 2) 如果您确实需要该功能,您可以编写一个客户函数来使其工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 2010-11-26
  • 1970-01-01
  • 2015-11-18
相关资源
最近更新 更多