Often the data in the CMS is in so big quantities that it is never displayed at once. We should have this in mind when working with the API, and only request the data that we need from the database (as opposed to requesting all of it, and then throwing some of it away).
The Sitefinity CMS API provides easy methods to do this, and you should always use them if you can. The main two scenarios that cover such cases are paging and filtering.
If you are displaying a paged list of items, always request only the currently visible page. Leave the database to decide which items you want, instead of taking all of them and doing the processing manually. The two methods of IQueryable that let you page through the result of a query are Take() and Skip().
The integer parameter X that you pass to Skip() tells the query to not return items 0 to X-1 and start from there. The integer parameter Y that you pass to Take() tells the query to return only Y items in the result. Y is equal to the page size. X is equal to the current page times the page size.
If we have a page size of 20 and want to display the 3rd page of items, our call would look something like:
We skip two pages (of 20 items each), and then take one page (of 20 items).
Often we want to filter the result of a query by a custom filter. Let’s say we want only news from a particular author. In this case, we can again offload the processing to the DB and get the filtered result directly, rather than filtering in memory. For the purpose we can use the Where() method of IQueryable. It allows us to pass any filter using a lambda expression. Filtering by author would look like this:
App.WorkWith().NewsItems().Get().Where(n => n.Author ==
The beauty of all IQueryable methods is that we can chain them and preserve For developers: Use LINQ deferred execution. No matter how many filters we want to stack on top of each other, the actual call to the database is still made only once, and right before needed. Expanding on the examples we’ve given, let’s say that Bill Gates has written a lot of articles and we want to page through them, displaying the third page of 20 news items. We can do it with the following call:
App.WorkWith().NewsItems().Get().Where(n => n.Author == “Bill Gates”).Skip(40).Take(20);
We can even chain several Where() calls one after another. As a rule, remember that when requesting data from the Sitefinity CMS API, you should always request only what you need. Using the IQueryable methods Skip(), Take() and Where() to do this moves the processing from your web server to the database server, and doesn’t waste your valuable resources.
Back To Top