How to use predicate builder with linq2sql and OR operator

感情迁移 提交于 2019-12-01 07:12:19

问题


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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/2690298/how-to-use-predicate-builder-with-linq2sql-and-or-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!