如何在EF中执行此动态where子句

时间:2014-07-24 21:26:37

标签: sql entity-framework

寻找有关如何使用EF处理以下选择查询的一些建议。

*注意,我只需要通过EF帮助SELECT,创建表/插入内容只是为了我的表结构样本

  CREATE TABLE SampleTable(Foo INT, Bar VARCHAR(50))

INSERT SampleTable VALUES 
    (1,'GoodData'),
    (2, 'BetterData'),
    (2, 'Whatever'),
    (10, 'GoodData')


SELECT
    *
FROM
    SampleTable st
WHERE
    (Foo = 2 AND Bar = 'BetterData')
    OR (Foo = 1 AND Bar = 'GoodData') --There could be a 1000 of these line 'OR' lines


DROP TABLE SampleTable

3 个答案:

答案 0 :(得分:1)

LINQ中还有另一个名为 system.linq.dynamic

的命名空间

如果您想通过代码运行时动态地进行查询,那将非常有用。

看看吧!!

答案 1 :(得分:0)

.Where(sampleTable => sampleTable.Foo == 2 && sampleTable.Bar == "BetterData") ||
    sampleTable.Foo == 1 && sampleTable.Bar == "GoodData").ToList();

答案 2 :(得分:0)

以下是一些可以提供帮助的扩展方法:

 public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>() { return f => true; }
    public static Expression<Func<T, bool>> False<T>() { return f => false; }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                         Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}

然后将其用于动态查询需求:

 Expression<Func<SampleTableObject, bool>> predicate = PredicateBuilder.True<SampleTableObject>(); 
 foreach(var item in conditionsList)
 {
     predicate = predicate.Or(x=>x.Foo == item.Foo && x.Bar == item.Bar);
 }

 var data = EFContext.SampleTableObjects.Where(predicate);