检测应用至IQueryable的< T> [英] Detect where applied to IQueryable<T>

查看:172
本文介绍了检测应用至IQueryable的< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能检测一个的IQueryable< T> 已应用了其中,过滤器



在此代码,我需要以编程知道 queryFiltered 有一个其中,适用于它和查询

 的IQueryable<客户>查询= Context.Customers; 
&IQueryable的LT;客户> queryFiltered = Context.Customers
。凡(C => c.Name.Contains(ABC));


解决方案

您将不得不解析的 表达式 一个从 表达式<返回/ code>在 href=\"http://msdn.microsoft.com/en-us/library/bb351562.aspx\" rel=\"nofollow\"> IQueryable的< T> 实施



您必须查询的的 Queryable.Where 方法被称为当你抓取表达树。



同时还要注意 Queryable.Where 将是检测其中,过滤器最常用的方式,查询语法允许被使用其他实现(具体取决于使用何种命名空间 使用指令 );如果您有没有使用 Queryable.Where 扩展方法的东西,然后你就必须寻找那些明确(或使用了<$过滤更宽泛的方法C $ C>这需要在哪里方法的的IQueryable< T> 并返回的IQueryable< T> )。



ExpressionVisitor (作为的所指出的萨那托斯)提供爬行表达树的一个非常简单的方法,我强烈建议使用这种方法为处理您的表达式树基地。



值得注意的是, ExpressionVisitor 需要类实现存储和在类级别暴露状态。正因为如此,这将是最好的(IMO)创建执行动作一次内部类,然后有创造的 ExpressionVisitor 每一个新实例的公共方法时间;这将有助于应对突变状态,如果处理得当,将允许该方法是线程安全的,以及(如果这是你的关注)。


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 Expression that is returned from the Expression property on the IQueryable<T> implementation.

You'll have to query for the Queryable.Where method being called as you crawl the Expression tree.

Also note that while Queryable.Where is going to be the most common way to detect a where filter, query syntax allows for other implementations to be used (depending on what namespaces are used in the using directives); if you have something that is not using the Queryable.Where extension method then you'll have to look for that explicitly (or use a more generic method of filtering for a Where method that takes an IQueryable<T> and returns an IQueryable<T>).

The ExpressionVisitor class (as pointed out by xanatos) provides a very easy way of crawling the Expression tree, I highly recommend using that approach as a base for processing your Expression tree.

Of note is that ExpressionVisitor class 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 the ExpressionVisitor every 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).

这篇关于检测应用至IQueryable的&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆