我想在 Linq 语句中动态生成跨越多个表的谓词。在以下代码片段中,我想使用 PredicateBuilder 或类似的构造来替换以下代码中的“where”语句:
代替:
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;
}
有类似的东西:
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);
}
有什么想法、想法、策略来解决这个问题?
谢谢,
欧拉算子