Search code examples
c#entity-frameworkasp.net-web-apiodata

How to set the count when calling a stored procedure in odata


I am using OData to get records, but due to some performance issues we are having when using the SQL it generates via LINQ, we have decided to write a stored procedure to get the data (using SQL Server as our database). I know how to call the stored procedure and map the result to an entity. The thing I am confused about is when I get an $inlinecount=allpages parameter, how do I manually set the odata.count parameter instead of having OData try to do it?

I'd like to call my stored procedure, which takes in all the filters and sorts, as well as skip and top for paging, as parameters, to get the data. The problem is, I need the total count (without applying the skip/top/sorts) for the odata.count property that should be returned in the response. To even get this count, I would have to either make a second stored procedure that only takes the filters and returns a count, or possibly modify the original one to return a count as an output parameter, along with the data. Regardless, once I get that number, what do I do with it? How do I tell OData to use that as the returned odata.count property, instead of trying to apply its own magic to do so?


Solution

  • If you profile the db when entity framework generates the query, it executes two queries. One for the total count and another for the data. Like you say, it is a similar query, just getting the count instead of the actual data.

    As far as how to return it, I have done so in the past using a PageResult<T> - this has a structure to include the count.

    You should also consider how you will handle other odata query options, like select. Or, you can disable options that you don't support.