2010-04-22 51 views
2

我有两个表(TABLE1,TABLE2-我知道唯一),它们分别具有一对多关系和两个表的ID列之间的外键。如何使用谓词生成器与linq2sql和OR运算符

使用LINQ2SQL我想选择所有TABLE1项,使得其相应的TABLE2值包含在我通过它的列表中至少1项。

下面是我用一些示例代码中LINQPad(真棒程序)来测试它不过正在错误NotSupportedException异常:用于查询操作“任何”不支持过载。

long[] items = { 3, 5, 8 }; 
var predicate = PredicateBuilder.False<TABLE2>(); 

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

当使用LinqKit在LinqPad添加参考LinqKit.dll,取消包含PredicateBuilder然后还附加命名空间进口标签下添加LinqKit。

+0

在这里找到了类似的问题http://stackoverflow.com/questions/2522079/generated-sql-with-predicatebuilder-linqpad-and-operator-any。没有在VS中进行过测试,但似乎可能是我在LINQPad中编写它的问题。 – David 2010-04-22 11:53:06

回答

2

解决方法是在TABLE1 对象

  • 呼叫编译()

    1. 呼叫AsExpandable()上表达 变量,上EntitySet的使用时。

    因此,最终的查询是

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

    更多信息here