我看到了一个相关的链接topic,但是...
我正在尝试实现规范模式。如果我使用
感谢 @Jon Skeet。
我正在尝试实现规范模式。如果我使用
System.Linq.Expressions
API显式地创建Or或And表达式,我会收到错误消息
例如,这是我的代码: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 中的规范模式,在我的工作代码中它看起来像:
EDITED
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。
编辑过的内容:
因此,我的解决方案是
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。