如何通过linq2sql和OR运算符使用谓词生成器 [英] How to use predicate builder with linq2sql and OR operator

查看:76
本文介绍了如何通过linq2sql和OR运算符使用谓词生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two tables (TABLE1, TABLE2 - unique i know) that has a 1-to-many relationship respectively and a foreign key between ID columns of both tables.

使用 linq2sql ,我试图选择所有 TABLE1 条目,以使它们对应的 TABLE2 值在我通过的列表中至少包含1个项目它.

Using linq2sql I am trying to select all TABLE1 entries such that their corresponding TABLE2 values contains at least 1 item in the list I pass it.

这是我在 LINQPad (超赞程序)中使用的一些示例代码对其进行测试,但是却收到错误 NotSupportedException:查询运算符"Any"使用了不受支持的重载.

Here's some sample code I was using in LINQPad (awesome program) to test it out however am getting the error NotSupportedException: Unsupported overload used for query operator 'Any'.

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();

更新

在LinqPad中使用LinqKit时,请添加对LinqKit.dll的引用,取消选中包括PredicateBuilder",然后在其他命名空间导入"选项卡下添加LinqKit.

When using LinqKit in LinqPad add the reference to LinqKit.dll, uncheck Include PredicateBuilder and then also add LinqKit under Additional Namespace Imports tab.

推荐答案

解决方法是

  1. TABLE1上调用AsExpandable() 对象
  2. 在表达式上调用Compile() 变量,当在EntitySet上使用时.
  1. Call AsExpandable() on the TABLE1 object
  2. Call Compile() on the expression variable, when used on an EntitySet.

所以您的最终查询是

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

更多信息此处.

这篇关于如何通过linq2sql和OR运算符使用谓词生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆