Adding a custom navigation property to OData Web API Controller

百般思念 提交于 2019-12-11 02:57:55

问题


I have an OData v3 Web API project. 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. 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).

The ODataConventionModelBuilder() is not picking up ItemRequirement as a navigation property

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. I have found by adding an IODataRoutingConvention implementor that the ODataPath is set to navigation/key/unresolved.

I looked at this solution and it didn't help me, either:

Adding a custom query backed Navigation Property to ODataConventionModelBuilder

I don't know if the problem is the inheritance, the fact that the property is not mapped in EF, or what.

I have also found that this fails with a 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?


回答1:


Can you try adding the navigation property explicitly?

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


来源:https://stackoverflow.com/questions/25004570/adding-a-custom-navigation-property-to-odata-web-api-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!