1

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();
Spectre87
  • 2,374
  • 1
  • 24
  • 37

2 Answers2

1

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.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
0

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).

Hadi Eskandari
  • 25,575
  • 8
  • 51
  • 65
  • Thanks for answering, but I think you misunderstood my question. I know there's no "Selected" event in IQueryable. I was talking about the LinqDataSource (asp.net control). My question is specific to the LinqDataSource, and not to Linq in general. I'm using a ListView/DataPager/LinqDataSource combo to handle paging the data. If it weren't for the DataPager, what I'm asking about would be very simple. But since not all the results are returned, I need a copy of the IQueryable query object that the LinqDataSource will use to get data. – Spectre87 May 31 '12 at 01:06
  • I need the IQueryable object _before_ it is executed, so that I can make a copy of it to also retrieve the total count in a category, and not just the rows on a "page". – Spectre87 May 31 '12 at 01:08
  • I suppose it would also need to be before the DataPager has added its `.Skip(x).Take(y)` query. The basic principle behind what I'm trying to accomplish is that the IQueryable doesn't actually contain any data before it is enumerated - it is basically just a query. So I'm trying to get it, then, copy, modify, and execute (enumerate) the modified version. – Spectre87 May 31 '12 at 01:19