Webapi odata expand with entity framework functions

后端 未结 2 1614
天涯浪人
天涯浪人 2021-01-06 20:46

I have a Product odata controller and a Product Category odata controller.
They are both using entity framework entities and have navigation methods used for odata expan

2条回答
  •  生来不讨喜
    2021-01-06 21:30

    Here is the code I used to fix the problem.
    By no means is it "correct" code.
    For example: ODataQueryOptions.Top / Skip will be null if used on an Action that contains ODataActionParameters.
    ODataActionParameters will contain the Top / Skip as a parameter? Very odd.
    So I added both in the hopes that Microsoft or someone else can fix this issue in the future.

    Controller:

    [HttpPost]
    [EnableQuery]
    public PageResult SomeFunction(ODataQueryOptions options, ODataActionParameters parameters)
    {
        // Get the paging settings from ODataActionParameters since they are not shown on the ODataQueryOptions. Maybe there will be some fix for this in the future.
        int pageSize = (int)parameters["pageSize"];
        int take = (int)parameters["take"];
        int skip = (int)parameters["skip"];
        int page = (int)parameters["page"];
    
        // Apply page size settings
        ODataQuerySettings settings = new ODataQuerySettings();
    
        // Create a temp result set to hold the results from the stored procedure
        var tempResults = db.SomeStoredProc().ToList(); // ToList is required to get the "real" total count before paging
    
        // Apply the query options. For now this is only needed to get the correct count since the options does not seem to contain the TOP / SKIP when using OData parameters.
        IQueryable results = options.ApplyTo(tempResults.AsQueryable(), settings);
    
        // This was needed for custom paging. EXAMPLE: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options
        return new PageResult(tempResults.Skip(skip).Take(take),
                                Request.ODataProperties().NextLink,
                                Request.ODataProperties().TotalCount);
    }
    

    Then WebApiConfig:

    var SomeFunction = builder.Entity().Collection.Action("SomeFunction");
    SomeFunction.Parameter("take");
    SomeFunction.Parameter("skip");
    SomeFunction.Parameter("page");
    SomeFunction.Parameter("pageSize");
    SomeFunction.ReturnsCollectionFromEntitySet("SomeObjects");
    

提交回复
热议问题