在没有PredicateBuilder的情况下将动态谓词添加到表达式中

时间:2018-11-11 12:53:16

标签: c# entity-framework linq entity-framework-6 linq-to-entities

我使用linqToEntities,并希望动态添加OR条件。

我知道there is a great library PredicateBuilder by brother Albahari可以解决我的任务,但是我不能使用它。

我的情况如下:

IEnumerable<Condition> conditions = new List<Condition>()
{
    new Condition(){IdReference = 1, TableName = "Table1" },
    new Condition(){IdReference = 2, TableName = "Table2" },
    new Condition(){IdReference = 3, TableName = "Table3" }, 
    // and so on
};

我拥有的是:

var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)
{
     //What code should be here to be translated into:
     /*
     histories = histories
        .Where(h => h.IdReference == 1 && h.TableName =="Table1" 
            || h.IdReference == 2 && h.TableName == "Table2"
            || h.IdReference == 3 && h.TableName == "Table3");
            // and so on
     */
}    

但是,我事先不知道多少conditions。 如何从OR动态添加IEnumerable<Condition>条件?

2 个答案:

答案 0 :(得分:2)

不确定使用谓词生成器有什么问题-不一定是LINQ Kit包,所谓的谓词生成器通常是具有2个扩展方法的单个静态类-例如Universal Predicate Builder或我自己的{ Establish a link between two lists in linq to entities where clause中的{1}}和类似的内容。

无论如何,当然,只要使用简单的Expression类静态方法即可构建它。

添加以下内容,以消除在每次调用前写PredicateUtils的需要:

Expression.

,然后使用类似这样的内容:

using static System.Linq.Expressions.Expression;

答案 1 :(得分:0)

据我了解您的意思

var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)
{
     //What code should be here to be translated into:

     histories = histories
        .Where(h => h.IdReference == cond.IdReference && 
      h.TableName ==cond.TableName );

}