这段代码工作正常:
ICriteria criteria = GetSession().CreateCriteria<MyClass>();
criteria.Add(Restrictions.Where<MyClass>(x => x.Field1 >= myVariable));
但是下面的代码不起作用:
criteria.Add(Restrictions
.Where<MyClass>(x =>
(x.Field1 +
x.Field2 +
x.Field3 +
x.Field4) >= myVariable));
上面的代码在执行时出现这个错误:
Variable 'x' of type 'myClass' referenced from scope '', but it is not defined
请帮忙(抱歉我的英语不好)。
萨拉
编辑 1
我的临时解决方案是:
var result = criteria.List<MyClass>();
result.Where(x => (x.Field1 + x.Field2 + x.Field3 + x.Field4 >= myVariable));
和这项工作。我宁愿在选择之前放置 Where 子句...
编辑2
最终的解决方案是(根据@mhoff 的建议):
var result = criteria.List<MyClass>();
result.Where(x => this.GetSum(x) >= myVariable);
... do something ...
... ToList()
private int GetSum(MyClass x) {
return (x.Field1 + x.Field2 + x.Field3 + x.Field4);
}
最佳答案
如何将您的计算转换为属性(这也有封装 MyClass 细节的好处):
public class MyClass
{
public int GetSum
{
get { return Field1 + Field2 + Field3 + Field4; }
}
}
criteria.Add(Restrictions.Where<MyClass>(x => x.GetSum > myVariable));
关于c# - 从范围 'x' 引用类型为 'myClass' 的错误变量 '',但未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11987454/