Does it make sense for an ASP.NET Web API method to return IQueryable<T>?
Asked Answered
P

1

5

I'm working on a project that uses the new Web API and I noticed somebody is returning an IQueryable<T> from a Get method.

My understanding is that IQueryable is useful for improving performance (deferred execution), but I don't think a client on the other end of an HTTP connection is going to be able to take advantage of that.

My gut is telling me that this should be IEnumberable<T>instead. Am I right about this?

Pekin answered 9/4, 2012 at 17:49 Comment(0)
I
8

Responses to methods returning IQueryable<T> can be "queried" by passing some odata-like parameters in the query string ($top, $skip, $filter, $orderby). For example, if your resource can be found at .../api/People, you can send those requests, which will cause the server to return different data:

.../api/People?$top=10                    ==> return only the first 10 elements
.../api/People?$skip=10&$top=5            ==> return the 11th to 15th elements
.../api/People?$filter=Name%20eq%20'John' ==> Only return people named "John"
.../api/People?$orderby=Name&$top=10      ==> return the first 10 elements, ordered by name

Notice that on the beta release any operation which returns IQueryable<T> automatically has this "querying" support added to it. On the latest bits (from codeplex), you need to manually add a [Queryable] attribute to the operation to enable this behavior.

If you don't want that querying behavior, then yes, returning IEnumerable<T> is just fine.

Illimitable answered 9/4, 2012 at 19:56 Comment(2)
I can't seem to find this 'Queryable' attribute in the release version of MVC Web API; how do I implement IQueryable<T> now?Nonbelligerent
I had to install the 'Microsoft.AspNet.WebApi.OData -Pre' package from NumGet.Nonbelligerent

© 2022 - 2024 — McMap. All rights reserved.