Search code examples
asp.net-mvc-4asp.net-web-apiodataiqueryable

How to format iqueryable mvc 4 web api requests?


I'd like to use iqueryable on all my collections so that I get all of the odata features. However I need to format the response of the request with the following fields;

{
   href: "url to resouce",
   length: 10,
   items: [
     "(IQueryable results)"
   ]
}

Formatting the response isnt the hard part but keeping all of the odata "stuff" working is.

So my code looks like;

MyFormattedResponse.Href = "poop.com";
MyFormattedResponse.Length = 0;
MyFormattedResponse.Items = _myRepo.Gets();
Request.CreateResponse(HttpStatusCode.OK, MyFormattedResponse);

But the error I get is:

The action 'Get' on controller 'MyResource' with return type 'MyObject' cannot support querying. Ensure the type of the returned content is IEnumerable, IQueryable, or a generic form of either interface.

Is this something I can construct in a media formatter or perhaps a filter?

I really want to keep the odata awesomeness...


Solution

  • Take a look at this answer I've provided:

    Web API Queryable - how to apply AutoMapper?

    Your case is similar, you can do something like this:

    public MyFormattedResponse Get(ODataQueryOptions<Person> query)
    {
        var results = query.ApplyTo(_myRepo.Gets()) as IEnumerable<Person>;
        return new MyFormattedResponse() { Href = "foo.com", Length = 5, Items = results };
    }
    

    Make sure you remove the [Queryable] attribute.