使用变量构建Linq表达式

时间:2009-08-31 00:05:54

标签: linq entity-framework lambda

我正在使用Linq和实体框架。我有一个页面实体,它与标记实体有多对多的关系。

我想创建一个Linq查询,该查询提取与所有提供的标签匹配的所有页面(以Int64 []的形式)。

我尝试了各种WhereIn和BuildContainsExpression示例,但没有一个按预期工作。

我现在正试图遍历每个标签并构建表达式列表:

 foreach (Int64 item in Tags)
 {
    Expression<Func<Pages, bool>> tagFilter = c => c.Tags.Any(x => x.TagID == item);
    exp.Add(tagFilter);
 }

但是,我认为局部变量“item”正在搞乱查询,因为它要么使用一个标记,要么在查询运行时都不使用它们,但是如果我这样指定它们:

 Expression<Func<Pages, bool>> tagFilter1 = c1 => c1.Tags.Any(x => x.TagID == 70);
 exp.Add(tagFilter1);
 Expression<Func<Pages, bool>> tagFilter2 = c1 => c1.Tags.Any(x => x.TagID == 130);
 exp.Add(tagFilter2);
 Expression<Func<Pages, bool>> tagFilter3 = c1 => c1.Tags.Any(x => x.TagID == 77);
 exp.Add(tagFilter3);

例如,使用实际数字“70”,它就像一个魅力。我基本上将表达式存储在列表中,并使用LinqKit和And()它们。

有没有办法保持这种动态?

1 个答案:

答案 0 :(得分:4)

将您的代码更改为:

foreach (Int64 item in Tags)
{
    var temp = item; // this variable is scoped **inside** the loop.
    Expression<Func<Pages, bool>> tagFilter = c => c.Tags.Any(x => x.TagID == temp);
    exp.Add(tagFilter);
}

有关详细说明,read my answer to the "What is the exact definition of a closure?" question

相关问题