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 o
I think your problem is with the type T of your PredicateBuilder - half of your predicate if acting on a Foo, the other half is on a Bar.
You could replace this with a simple manually constructed query:
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
select new {Foo = foo, Bar = bar};
if (searchName)
{
query = query.Where(fb => fb.Foo.Name == "fooname");
}
if (searchDescription)
{
query = query.Where(fb => fb.Bar.Description == "barstring");
}
// use query here
}
An alternative method is to use PredicateBuilder but to make it work on the Foo,Bar couple - e.g.
class FooBar
{
public Foo Foo {get;set;}
public Bar Bar {get;set;}
}
void Test(bool searchName, bool searchDescription)
{
IQueryable<Foo> fooQuery = null; // Stubbed out
IQueryable<Bar> barQuery = null; // Stubbed out
var query =
from foo in fooQuery
join bar in barQuery on foo.FooId equals bar.FooId
select new FooBar
{
Foo = foo,
Bar = bar
};
var predicate = PredicateBuilder.False<FooBar>();
if (searchName)
{
predicate = predicate.Or(foobar => foobar.Foo.Name == "fooname");
}
if (searchDescription)
{
predicate = predicate.Or(foobar => foobar.Bar.Description == "barstring");
}
query = query.Where(predicate);
// use query here
}