Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 852
Andy West Avatar asked Apr 09 '12 17:04

Andy West


1 Answers

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.

like image 141
carlosfigueira Avatar answered Jan 01 '23 14:01

carlosfigueira