Expression.Lambda:类型“变量" x,从范围“引用",但未定义 [英] Expression.Lambda: Variable 'x' of type '' referenced from scope '', but it is not defined

查看:143
本文介绍了Expression.Lambda:类型“变量" x,从范围“引用",但未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到已连接主题,但是...

I saw connected topic but...

我正在尝试实现规范模式.如果我使用System.Linq.Expressions API显式创建Or或And表达式,则会收到错误

I was attempting to implement specification pattern. If I create the Or or And Expression explicitly with the System.Linq.Expressions API, I will get the error

从作用域引用的InvalidOperationExpression变量'x'.

InvalidOperationExpression variable 'x' referenced from scope.

例如,这是我的代码

public class Employee
{
    public int Id { get; set; }
}

Expression<Func<Employee, bool>> firstCondition = x => x.Id.Equals(2);
Expression<Func<Employee, bool>> secondCondition = x => x.Id > 4;


Expression predicateBody = Expression.OrElse(firstCondition.Body, secondCondition.Body);
Expression<Func<Employee, bool>> expr = 
    Expression.Lambda<Func<Employee, bool>>(predicateBody, secondCondition.Parameters);
Console.WriteLine(session.Where(expr).Count()); - //I got error here

已编辑

我试图对Linq to Nhibernate使用规范模式因此在我的工作代码中,它看起来像:

I tried to use Specification pattern with Linq to Nhibernate so in a my work code it looks like:

ISpecification<Employee> specification = new AnonymousSpecification<Employee>(x => x.Id.Equals(2)).Or(new AnonymousSpecification<Employee>(x => x.Id > 4));
var results = session.Where(specification.is_satisfied_by());

所以我想使用类似x => x.Id> 4的代码.

So I want to use code like this x => x.Id > 4.

已编辑

所以我的解决方法是

 InvocationExpression invokedExpr = Expression.Invoke(secondCondition, firstCondition.Parameters);
var expr = Expression.Lambda<Func<Employee, bool>>(Expression.OrElse(firstCondition.Body, invokedExpr), firstCondition.Parameters);
Console.WriteLine(session.Where(expr).Count());

谢谢@Jon Skeet

Thank you @Jon Skeet

推荐答案

这些实体中的每个实体都有一组单独的参数,因此仅使用secondCondition.Parameters不会给firstCondition.Body一个参数.

Each of those bodies has a separate set of parameters, so using just secondCondition.Parameters doesn't give firstCondition.Body a parameter.

幸运的是,您根本不需要自己编写所有这些内容.只需使用Joe Albahari的 PredicateBuilder -一切都为您完成了.

Fortunately, you don't need to write all of this yourself at all. Just use PredicateBuilder by Joe Albahari - it's all done for you.

这篇关于Expression.Lambda:类型“变量" x,从范围“引用",但未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆