3

我有一个使用 EF 4.4 的存储库和一个具有可用于过滤查询的参数的类。另外,我使用 SQLQuery 创建我的动态原始 sql,以根据我的参数类的属性添加条件,这些属性不为空。

但是,SQL Query 不允许预先加载,所以我想知道如何使用 LinQ 创建动态查询以便能够使用预先加载。

我读过这篇文章

使用参数类,但只使用一个参数进行查询,但是如果类中有很多参数并且我有很多组合,怎么办?如果要考虑所有可能的组合,我还需要做很多其他事情吗?当我使用原始 sql 时,我只需要检查一个参数是否为空,如果不为空,只检查是否是第一个添加“where”的参数,或者是否添加了“and”。所以代码很短,因为我不需要考虑所有可能的参数组合。

如何使用 LinQ 进行动态查询?

谢谢。

4

2 回答 2

3
var query = ctx.Books;

if ( param1 != null )
   query = query.Where( b => b.Param1 == param1 );

if ( another2 > 0 )
   query = query.Where( b => b.Amount > another );

等等

如您所见,子句是根据任意外部标准动态组合的,最终让您完全控制查询结构。

请注意,EF 仍将其作为单个数据库查询执行。

于 2013-06-15T09:14:59.910 回答
1

你可以这样做:

bool consider1stParam = is it not null?
bool consider2ndParam = is it not null?
bool consider3rdParam = is it not null?
... //And so on for each parameter you wish to include in the query

然后,使用与此类似的语法进行查询(假设我们处理用户):

users = users
        .Where(u => (consider1stParam && (Your 1st param examination here)) ||
                        (consider2ndParam && (Your 2nd param examination here)) ||
                        (consider3rdParam && (Your 3rd param examination here)) 
                     ... and so on);

这将根据之前的设置将“过滤器”添加到 where 查询中。

同样,您可以将其稍微更改为“与”过滤器而不是“或”过滤器。

于 2013-06-15T10:11:33.937 回答