I would like to dynamically generate predicates that span multiple tables across a Join in a Linq statement. In the following code snippet, I want to use PredicateBuilder or a similar construct to replace the 'where' statement in the following code:
Replace:
public class Foo
{
public int FooId; // PK
public string Name;
}
public class Bar
{
public int BarId; // PK
public string Description;
public int FooId; // FK to Foo.PK
}
void Test()
{
IQueryable<Foo> fooQuery = null; // Stubbed out
IQueryable<Bar> barQuery = null; // Stubbed out
IQueryable<Foo> query =
from foo in fooQuery
join bar in barQuery on foo.FooId equals bar.FooId
where ((bar.Description == "barstring") || (foo.Name == "fooname"))
select foo;
}
With something like:
void Test(bool searchName, bool searchDescription)
{
IQueryable<Foo> fooQuery = null; // Stubbed out
IQueryable<Bar> barQuery = null; // Stubbed out
IQueryable<Foo> query =
from foo in fooQuery
join bar in barQuery on foo.FooId equals bar.FooId
select foo;
// OR THIS
var query =
from foo in fooQuery
join bar in barQuery on foo.FooId equals bar.FooId
select new {foo, bar};
var predicate = PredicateBuilder.False<Foo>();
if (searchName)
{
predicate = predicate.Or(foo => foo.Name == "fooname");
}
if (searchDescription)
{
// Cannot compile
predicate = predicate.Or(bar => bar.Description == "barstring");
}
// Cannot compile
query = query.Where(predicate);
}
Any thoughts, ideas, strategies for tackling this problem?
Thanks,
EulerOperator