I saw connected topic but...
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 variable 'x' referenced from scope.
For example ,this is my code
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
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());
So I want to use code like this x => x.Id > 4.
Edited
So my solution is
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());
Thank you @Jon Skeet