Limiting how many entities are returned from an ADO.NET Data Service

If you want to limit the number of entities returned from a service, you have a few alternatives...

If you're writing code for the client, the easiest way is to just use the '$top' clause to limit how many entities will be returned. Note that '$top' doesn't account for entities you expand using '$expand', so be careful with what you expand if you're using it.

That pretty much covers it for the options on the client - the server however is a more interesting thing.

First, you have the configuration options. MaxResultsPerCollection allows you to limit not only the number of entities returned at the top level of a request, but also at each collection within, so clients can't use '$expand' to overwhelm the server. Because a batch request can have multiple queries, you can combine that with MaxBatchCount.

The problem with using the configuration on the server is that it's meant more as a security feature than as a general paging mechanism, and as such the responses returned will (a) likely cause the client to error, because the response ends mid-stream, and (b) the client will have no good way to "continue" asking for data from where the last request left off.

A better approach might be to ask clients to be explicit about how many entities they're willing to handle at once using the '$top' option, and overriding the OnStartProcessingRequest method on the data service to check that the URL has indeed specified the '$top' option. Of course, you still want to set the configuration to safeguard your server!

Enjoy!