简体   繁体   English

将自定义导航属性添加到OData Web API Controller

[英]Adding a custom navigation property to OData Web API Controller

I have an OData v3 Web API project. 我有一个OData v3 Web API项目。 It uses an Entity Framework Code First model. 它使用实体框架代码优先模型。

The main class is Coupon. 主要课程是优惠券。 It has a List. 它有一个列表。 What this really is, is a 2-element collection of subtypes ItemRequirement and BasketRequirement. 实际上,这是子元素ItemRequirement和BasketRequirement的2元素集合。 I want to be able to say: 我想能够说:

../odata/Coupons(5)/ItemRequirement

I can NOT get this to work. 我无法使它正常工作。

First, in the EF class, I have added ItemRequirement as a [NotMapped] property (as the class already has a collection of the base class as a navigation property, and adding the other two as properties would just generate extraneous table keys and mess up the database unnecessarily. The Table-Per-Hierarchy in Code First is working great as is). 首先,在EF类中,我已将ItemRequirement添加为[NotMapped]属性(因为该类已经具有基类的集合作为导航属性,而将其他两个添加为属性只会生成无关的表键并弄乱代码优先级中的逐层表按原样工作)。

The ODataConventionModelBuilder() is not picking up ItemRequirement as a navigation property ODataConventionModelBuilder()未将ItemRequirement用作导航属性

I attempted to add it: 我试图添加它:

// GET odata/Coupons(5)/ItemRequirement
public ItemRequirement GetItemRequirement( [FromODataUri] decimal key)
{
   return db.Coupons.Where(m => m.CouponId == key).SelectMany(m => m.RedemptionPurchaseRequirements).OfType<ItemRequirement>().FirstOrDefault();
}

The URI will NEVER get into this code. URI永远不会进入此代码。 I have found by adding an IODataRoutingConvention implementor that the ODataPath is set to navigation/key/unresolved. 通过添加IODataRoutingConvention实现程序,我发现ODataPath设置为navigation / key / unresolved。

I looked at this solution and it didn't help me, either: 我查看了此解决方案,但它也没有帮助我:

Adding a custom query backed Navigation Property to ODataConventionModelBuilder 将自定义查询支持的导航属性添加到ODataConventionModelBuilder

I don't know if the problem is the inheritance, the fact that the property is not mapped in EF, or what. 我不知道问题是否出在继承,属性未在EF中映射的事实或什么。

I have also found that this fails with a 404: 我还发现这失败并显示404:

oData/PurchaseRequirementsBases(5)/myNamespace.ItemRequirement

Just what witchcraft is necessary to abstract the collection away so the OData consumer can see ItemRequirement as a valid property of Coupon? 到底有什么巫术才有必要抽象化集合,以便OData使用者可以将ItemRequirement视为Coupon的有效属性?

您可以尝试显式添加navigation属性吗?

odataConventionModelBuilder().Entity<Coupon>().HasOptional(coupon => coupon.ItemRequirement)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM