I’m wondering if it’s possible to write a “passthrough” extension method for IQueryable which would write a debugstring whenever the queryable is evaluated, in other words, the debug print should be a side-effect of evaluation.
Something like:
var qr = SomeSource.Where(...).OrderBy(...).Trace("SomeSource evaluated at {0}", DateTime.Now)
var qr2 = qr.Where(...);
When I construct a linq query and pass it as a data source to some object, I’d like to know when and how often does the object evaluate my query. I suppose it can be achieved in other ways, like for example wrapping IEnumerable.GetEnumerator, but I’d like to do it generically for any linq query.
I’ve done something similar, but more complex (because it also manipulates the expressions as it processes them). In order to accomplish it, I created a wrapper class that implemented IQueryable and contained a reference to the thing I actually wanted to query. I made it pass all interface members through to the referenced object except for the Provider property, which returned a reference to another class I created that inherited from IQueryProvider. IQueryProvider has the methods that get called whenever a query is constructed or executed. So you could do something like this if you don’t mind being forced to always query your wrapper object(s) instead of the original object(s).
You should also be aware, if you’re using LINQ-to-SQL, there’s a Log property on the DataContext that you can use to route lots of debug information wherever you want.
Sample code:
Make your own IQueryable to control the QueryProvider that gets returned.
Make a custom query provider to control the expression tree that gets generated.
Then extend your derived DataContext by providing wrapped queryables: