簡體   English   中英

OData v4自定義功能

[英]OData v4 Custom Function

我正在嘗試在OData v4 Web API解決方案中創建自定義函數。 我需要返回基於OData本身無法處理的獨特邏輯的“Orders”集合。 我似乎無法弄清楚如何在不破壞整個OData服務層的情況下創建這個自定義函數。 當我使用ODataRoute屬性修飾Controller方法時,它都會變成地獄。 任何基本請求都會產生相同的錯誤。 有人可以看看下面的代碼,看看你是否注意到我必須遺漏的東西?

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.MapODataServiceRoute("odata", "odata", model: GetModel());
    }

    public static Microsoft.OData.Edm.IEdmModel GetModel()
    {
        ODataModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<Account>("Accounts");
        builder.EntitySet<Email>("Emails");
        builder.EntitySet<PhoneNumber>("PhoneNumbers");
        builder.EntitySet<Account>("Accounts");
        builder.EntitySet<Address>("Addresses");
        builder.EntitySet<Order>("Orders");
        builder.EntitySet<OrderDetail>("OrderDetails");

        var orders = builder.EntityType<Order>();
        var function = orders.Function("GetByExternalKey");
        function.Parameter<long>("key");
        function.ReturnsCollectionFromEntitySet<Order>("Orders");

        return builder.GetEdmModel();
     }
 }

OrdersController.cs

public class OrdersController : ODataController
{
    private SomeContext db = new SomeContext();

    ...Other Stuff...

    [HttpGet]
    [ODataRoute("GetByExternalKey(key={key})")]
    public IHttpActionResult GetByExternalKey(long key)
    {
       return Ok(from o in db.Orders
          where //SpecialCrazyStuff is done
          select o);
    }
}
}

當針對OData層發出任何請求時,我收到以下錯誤響應。

控制器“Orders”中操作“GetByExternalKey”上的路徑模板“GetByExternalKey(key = {key})”不是有效的OData路徑模板。 找不到段'GetByExternalKey'的資源。

根據模型構建器,函數GetByExternalKey是一個綁定函數。 根據OData協議v4,通過名稱空間或別名限定命名調用綁定函數,因此您需要在route屬性中添加更多:

[HttpGet]
[ODataRoute("Orders({id})/Your.Namespace.GetByExternalKey(key={key})")]
public IHttpActionResult GetByExternalKey(long key)
{
   return Ok(from o in db.Orders
      where//SpecialCrazyStuff is done
      select o);
}

如果您不知道命名空間,只需在下面添加方法GetModel():

builder.Namespace = typeof(Order).Namespace;

並將“Your.Namespace”替換為Order類型的命名空間。

以下是與您的問題相關的2個示例,僅供參考: https//aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataFunctionSample/

https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataAttributeRoutingSample/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM