I saw a related topic , but ...
I tried to implement a specification template. If I create Or or Ex Expression explicitly using the System.Linq.Expressions API, I will get an error
InvalidOperationExpression variable 'x' referring to 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()); -
EDITED
I tried using the specification template with Linq to Nhibernate , so in my working code it looks like this:
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 decision
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());
Thanks @Jon Skeet
source share