How can I get the IQueryable object used by LinqDataSource?

582 views Asked by At

Is there a way to get the IQueryable object that the LinqDataSource has used to retrieve data? I thought that it might be possible from the selected event, but it doesn't appear to be.

Each row in my table has a category field, and I want to determine how many rows there are per category in the results.

I should also note that I'm using a DataPager, so not all of the rows are being returned. That's why I want to get the IQueryable, so that I can do something like

int count = query.Where(i => i.Category == "Category1").Count();
2

There are 2 answers

2
Gert Arnold On BEST ANSWER

Use the QueryCreated event. QueryCreatedEventArgs has a Query property that contains the IQueryable.

The event is raised after the original LINQ query is created, and contains the query expression before to it is sent to the database, without the ordering and paging parameters.

3
Hadi Eskandari On

There's no "Selected" event in IQueryable. Furthermore, if you're filtering your data on the server, there'd be no way you can access it, even if the API exposed it, but to answer a part of the question, let's say you have category -> product where each category has many products and you want the count of the products in each category. It'd be a simple LINQ query:

var query = GetListOfCategories();
var categoryCount = query.Select(c => c.Products).Count();

Again, depending on the type of object GetListOfCategories return, you might end up having correct value for all the entries, or just the ones that are loaded and are in memory, but that's the different between Linq-to-Objects (in memory) and Linq-to-other data sources (lazy loaded).