我正在使用NHibernate 3.0开发一个应用程序。我开发了一个Repository hat接受一个表达式来对QueryOver做一些过滤。我的方法是这样的:
public IEnumerable<T> FindAll(Expression<Func<T, bool>> filter) {
return Session.QueryOver<T>().Where(filter).List();
}
工作正常。所以,我也有一个Service层,这个服务中的My方法接受基本类型,如下所示:
public IEnumerable<Product> GetProducts(string name, int? stock, int? reserved) {
// how init the expression ?
Expression<Func<Product, bool>> expression = ???;
if (!string.IsNullOrEmpty(name)) {
//add AND condition for name field in expression
}
if (stock.HasValue) {
//add AND condition for stock field in expression
}
if (reserved.HasValue) {
//add AND condition for reserved field in expression
}
return _repository.FindAll(expression);
}
我的怀疑是:
有可能吗? Ta在必要时添加一些条件(当我的参数有值时)?
由于
///我的编辑
public ActionResult Index(ProductFilter filter) {
if (!string.IsNullOrEmpty(filter.Name) {
return View(_service.GetProductsByName(filter.Name))
}
// others conditions
}
///几乎是一个解决方案
Expression<Func<Product, bool>> filter = x => true;
if (!string.IsNullOrEmpty(name))
filter = x => filter.Compile().Invoke(x) && x.Name == name;
if (stock.HasValue)
filter = x => filter.Compile().Invoke(x) && x.Stock == stock.Value;
if (reserved.HasValue)
filter = x => filter.Compile().Invoke(x) && x.Reserved == reserved.Value;
return _repository.FindAll(filter);
答案 0 :(得分:2)
这是一种方法。我不打算对你正在做的事情进行编辑 - 它看起来像是逐个查询,这几乎总是有问题的。这是其他人最好避免的。表达的东西虽然很有趣 - 所以我觉得值得一试。
class MyClass
{
public string Name { get; set; }
public bool Hero { get; set; }
public int Age { get; set; }
}
我们希望像这样查询:
string name = null;
int? age = 18;
Expression<Func<MyClass, bool>> myExpr =
x => (string.IsNullOrEmpty(name) || x.Name == name) &&
(!age.HasValue || x.Age > (age ?? 0));
myExpr = myExpr.RemoveCloture(); // this line here - removes the cloture -
// and replaces it with constant values - and shortcuts
// boolean evaluations that are no longer necessary.
// in effect this expression now becomes :
// x => x.Age > 18
bool result = myExpr.Compile()(
new MyClass {Name = "Rondon", Hero = true, Age = 92});
所以你所要做的就是写RemoveCloture();
- 不是问题。
// using System;
// using System.Linq.Expressions;
public static class ClotureRemover
{
#region Public Methods
public static Expression<TExpressionType> RemoveCloture<TExpressionType>(
this Expression<TExpressionType> e)
{
var converter = new RemoveClotureVisitor();
var newBody = converter.Visit(e.Body);
return Expression.Lambda<TExpressionType>(newBody, e.Parameters);
}
#endregion
private class RemoveClotureVisitor : ExpressionVisitor
{
public RemoveClotureVisitor()
{
}
public override Expression Visit(Expression node)
{
if (!RequiresParameterVisitor.RequiresParameter(node))
{
Expression<Func<object>> funct = () => new object();
funct = Expression.Lambda<Func<object>>(Expression.Convert(node, typeof(object)), funct.Parameters);
object res = funct.Compile()();
return ConstantExpression.Constant(res, node.Type);
}
return base.Visit(node);
}
protected override Expression VisitBinary(BinaryExpression node)
{
if ((node.NodeType == ExpressionType.AndAlso) || (node.NodeType == ExpressionType.OrElse))
{
Expression newLeft = Visit(node.Left);
Expression newRight = Visit(node.Right);
bool isOr = (node.NodeType == ExpressionType.OrElse);
bool value;
if (IsBoolConst(newLeft, out value))
{
if (value ^ isOr)
{
return newRight;
}
else
{
return newLeft;
}
}
if (IsBoolConst(newRight, out value))
{
if (value ^ isOr)
{
return newLeft;
}
else
{
return newRight;
}
}
}
return base.VisitBinary(node);
}
protected override Expression VisitUnary(UnaryExpression node)
{
if (node.NodeType == ExpressionType.Convert || node.NodeType == ExpressionType.ConvertChecked)
{
Expression newOpperand = Visit(node.Operand);
if (newOpperand.Type == node.Type)
{
return newOpperand;
}
}
return base.VisitUnary(node);
}
private static bool IsBoolConst(Expression node, out bool value)
{
ConstantExpression asConst = node as ConstantExpression;
if (asConst != null)
{
if (asConst.Type == typeof(bool))
{
value = (bool)asConst.Value;
return true;
}
}
value = false;
return false;
}
}
private class RequiresParameterVisitor : ExpressionVisitor
{
protected RequiresParameterVisitor()
{
result = false;
}
public static bool RequiresParameter(Expression node)
{
RequiresParameterVisitor visitor = new RequiresParameterVisitor();
visitor.Visit(node);
return visitor.result;
}
protected override Expression VisitParameter(ParameterExpression node)
{
result = true;
return base.VisitParameter(node);
}
internal bool result;
}
}
答案 1 :(得分:1)
首先,我首先要避免它来解决你的问题。我有不同的方法。
public IEnumerable<Product> GetProductsByName(string name)
public IEnumerable<Product> GetProudctsByNameAndStock(string name, int stock)
public IEnumerable<Product> GetProductsByNameAndReserved(
string name,
int reserved
)
public IEnumerable<Product> GetProducts(string name, int stock, int reserved)
就lambda表达式而言,这些都非常容易实现。例如:
public IEnumerable<Product> GetProductsByName(string name) {
return GetProductsByExpression(p => p.Name == name);
}
private IEnumerable<Product> GetProductsByExpression(
Expression<Func<Product, bool>> expression
) {
return _repository.FindAll(expression);
}
等
有可能吗? Ta在必要时添加一些条件(当我的参数有值时)?
其次,是的,你想做的事情是可能的,但这不是我解决问题的方式。
答案 2 :(得分:0)
您的存储库方法定义建议您将FindAll视为您传递条件并返回完成结果的内容。为什么不只是让结果为IQueryable类型并返回Session.QueryOver?
您的服务层将执行此类操作,将“wheres”链接在一起:
var query = _repository.FindAll();
if (!string.IsNullOrEmpty(name))
query = query.Where(x => x.Name == name);
if (stock.HasValue)
query = query.Where(x => x.Stock == stock);
etc...
return query.ToList();
答案 3 :(得分:0)
所以这就是你如何实际和lambdas在一起 - 它借用this awesome answer from desco的大部分代码值得投票。
public static class AddExpressions
{
public static Expression<Func<TFrom, TTo>> AndLambdas<TFrom, TTo>(this Expression<Func<TFrom, TTo>> first, Expression<Func<TFrom, TTo>> second)
{
ParameterExpression paramToUse = first.Parameters[0];
Expression bodyLeft = first.Body;
ConversionVisitor visitor = new ConversionVisitor(paramToUse, second.Parameters[0]);
Expression bodyRight = visitor.Visit(second.Body);
return Expression.Lambda<Func<TFrom, TTo>>(Expression.MakeBinary(ExpressionType.AndAlso, bodyLeft, bodyRight), first.Parameters);
}
class ConversionVisitor : ExpressionVisitor
{
private readonly ParameterExpression newParameter;
private readonly ParameterExpression oldParameter;
public ConversionVisitor(ParameterExpression newParameter, ParameterExpression oldParameter)
{
this.newParameter = newParameter;
this.oldParameter = oldParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return newParameter; // replace all old param references with new ones
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression != oldParameter) // if instance is not old parameter - do nothing
return base.VisitMember(node);
var newObj = Visit(node.Expression);
var newMember = newParameter.Type.GetMember(node.Member.Name).First();
return Expression.MakeMemberAccess(newObj, newMember);
}
}
}
然后调用代码非常简单....
class MyClass
{
public string Name { get; set; }
public bool Hero { get; set; }
public int Age { get; set; }
}
...
Expression<Func<MyClass, bool>> expression1 = x => x.Age > (age ?? 0);
Expression<Func<MyClass, bool>> expression2 = x => x.Name == name;
expression1 = expression1.AndLambdas(expression2);
result = expression1.Compile()(new MyClass {
Name = "Rondon",
Hero = true,
Age = 92 });