我看到已连接topic https://stackoverflow.com/questions/6106283/memberexpression-invalidoperationexpression-variable-x-referenced-from-scope but...
我试图实现规范模式。如果我使用显式创建 Or 或 And 表达式System.Linq.Expressions
API,我会收到错误
从作用域引用了 InvalidOperationExpression 变量“x”。
例如,这是我的代码
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
EDITED
我尝试使用Linq to Nhibernate 的规范模式 http://www.adamaldrich.com/blog/post/Specification-Pattern-and-Linq.aspx所以在我的工作代码中它看起来像:
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。
Edited
所以我的解决方案是
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());
谢谢你@乔恩斯基特