给定带有 Where 子句的查询
CollectionA.Where(a => a.Prop1 == val1 && a.Prop2 == val2)
和另一个具有类似 Where 子句但属性通过引用链接的查询。
CollectionB.Where(b => b.Reference.Prop1 == val1 && b.Reference.Prop2 == val2)
对于功能,这确实有效:
Func<A, bool> f1 = a => a.Prop1 == val1 && a.Prop2 == val2;
Func<B, bool> g1 = b => f1(b.Reference);
对于表达式,这不起作用:
Expression<Func<A, bool>> f2 = a => a.Prop1 == val1 && a.Prop2 == val2;
Expression<Func<B, bool>> g2 = b => f2(b.Reference); // <-- Method name expected.
我想使用规范在我的查询中重用表达式。
像这样:
Specification specification = new Specification(val1, val2)
CollectionA.Where(specification.ToExpression());
CollectionB.Where(specification.ToExpression(x => x.Reference));:
public class Specification
{
private readonly int val1;
private readonly long val2;
public Specification(int val1, long val2)
{
this.val1 = val1;
this.val2 = val2;
}
public Expression<Func<A, bool>> ToExpression()
{
return x => x.Prop1 == val1 && x.Prop2 == val2;
}
public Expression<Func<B, bool>> ToExpression<B>(Expression<Func<B, A>> navigate)
{
// ?
}
}
如何实现这个方法?
此外,我希望这不仅适用于二进制“和”表达式,还适用于任何表达式(即任何组合深度和参数类型)。(例如a => a.Prop1 == val1 && a.Prop2.Prop2a == val2a && a.Prop2.Prop2a == val2a
)但基本上它只是实现我尝试用上面的函数 g2 做的事情。