如何使用linq2sql和OR运算符使用谓词构建器

我有两个表(TABLE1,TABLE2 – 我知道的唯一),它们分别具有1对多关系,并且两个表的ID列之间有一个外键。

使用linq2sql我试图选择所有TABLE1条目,使其相应的TABLE2值包含我传递它的列表中的至少1项。

这是我在LINQPad (真棒程序)中使用的一些示例代码来测试它但是我得到错误NotSupportedException:用于查询运算符’Any’的不支持的重载。

long[] items = { 3, 5, 8 }; var predicate = PredicateBuilder.False(); foreach (long i in items) { long t = i; predicate = predicate.Or(att => att.ID == t); } //TABLE2.Where(predicate).Dump(); //works like a charm IQueryable query = from t1 in TABLE1 where t1.TABLE2.AsQueryable().Any(predicate) //problem with this line select a; query.Dump(); 

UPDATE

在LinqPad中使用LinqKit时,添加对LinqKit.dll的引用,取消选中Include PredicateBuilder,然后在Additional Namespace Imports选项卡下添加LinqKit。

解决方法是

  1. TABLE1对象上调用AsExpandable()
  2. 在EntitySet上使用时,对表达式变量调用Compile()。

所以你的最终查询是

 IQueryable query = from t1 in TABLE1.AsExpandable() where t1.TABLE2.Any(predicate.Compile()) //the problem should disappear select a; 

更多信息在这里 。