开发者

How to use predicate builder with linq2sql and OR operator

I have two tables (TABLE1, TABLE2 - unique i know) that has a 1-to-man开发者_JAVA百科y relationship respectively and a foreign key between ID columns of both tables.

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.

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

UPDATE

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


The workaround is

  1. Call AsExpandable() on the TABLE1 object
  2. Call Compile() on the expression variable, when used on an EntitySet.

So your final query is

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

More information here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜