如果您查看以下示例 oData 提要,您将看到包含的“子”项目的导航属性,以告诉您要遵循的 URL:
http://services.odata.org/OData/OData.svc/Suppliers?$format=json
例如,供应商 0 具有产品的导航属性。
这链接到该供应商的产品列表。
http://services.odata.org/OData/OData.svc/Suppliers(0)/Products?$format=json
我正在尝试对
ODataConventionModelBuilder
和 EntitySetController<Product>
做同样的事情,这样当我请求 oData/Product(0)
时,它会显示产品的“功能”:我像这样创建我的模型(基于 GetImplicitEdmModel sample )
// odata
ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<RRStoreDB.Models.Product>("Product");
modelBuilder.EntitySet<RRStoreDB.Models.ProductFeature>("ProductFeature");
Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
config.Routes.MapODataRoute("ODataRoute", "odata", model);
我为 WebAPI 创建了一个 Controller :
public class ProductController : EntitySetController<Product, int>
{
RRStoreDBContext _db = new RRStoreDBContext();
[Queryable]
public override IQueryable<DProduct> Get()
{
return _db.Products.AsQueryable();
}
public ICollection<ProductFeature> GetProductFeatures(int key)
{
Product product = _db.Products.FirstOrDefault(p => p.ProductId == key);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product.ProductFeatures;
}
}
当我实际调用我的子属性的 URL 时,它可以工作并为我提供正确的功能列表:
/oData/Products(18)/ProductFeatures
但是,我希望
/oData/Products(18)
中的导航属性指向此。我需要做什么才能让它出现。 This article 说它是自动的,但我没有看到它们:
The ODataConventionModelBuilder, which is generally recommended over the ODataModelBuilder, will automatically infer inheritance hierarchies in the absence of explicit configuration. Then once the hierarchy is inferred, it will also infer properties and navigation properties too. This allows you to write less code, focusing on where you deviate from our conventions.
最佳答案
我认为问题在于您要求 application/json
。 Web API OData 中的 application/json
指向 json light,这是最新的 OData json 表示,旨在减少响应有效负载大小并从响应中删除不必要/冗余的元数据。为了进行比较,请尝试使用接受 header ~/oData/Products(18)
获取 url application/json;odata=verbose
。
现在,json light 背后的想法是,如果由于链接遵循约定而可以计算链接,则不会将其放入响应中。导航链接 /oData/Products(18)/ProductFeatures
就是一个完美的例子。它遵循 OData uri 约定。
OData json light 有 3 种模式,minimummetadata(默认),fullmetadata 和 nometadata。名称本身就是解释性的。如果您希望链接在线,请发送带有接受 header application/json;odata=fullmetadata
的请求。
请参阅此 document 以了解有关 json light 的更多信息。
关于wcf-data-services - 为什么我的 oData 响应没有导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16455501/