How can I detect if a IQueryable<T> has a where filter applied?
In this code, I need to know programmatically that queryFiltered has a where applied to it and query doesn’t
IQueryable<Customer> query = Context.Customers;
IQueryable<Customer> queryFiltered = Context.Customers
.Where(c=>c.Name.Contains("ABC"));
You will have to parse the
Expressionthat is returned from theExpressionproperty on theIQueryable<T>implementation.You’ll have to query for the
Queryable.Wheremethod being called as you crawl theExpressiontree.Also note that while
Queryable.Whereis going to be the most common way to detect awherefilter, query syntax allows for other implementations to be used (depending on what namespaces are used in theusingdirectives); if you have something that is not using theQueryable.Whereextension method then you’ll have to look for that explicitly (or use a more generic method of filtering for aWheremethod that takes anIQueryable<T>and returns anIQueryable<T>).The
ExpressionVisitorclass (as pointed out by xanatos) provides a very easy way of crawling theExpressiontree, I highly recommend using that approach as a base for processing yourExpressiontree.Of note is that
ExpressionVisitorclass implementations are required to store and expose state on the class level. Because of that, it would be best (IMO) to create internal classes that perform the action one-time and then have a public method which creates a new instance of theExpressionVisitorevery time; this will help with dealing with mutating state, and if done properly, will allow the method to be thread-safe as well (if that is a concern of yours).