【问题标题】:Modifying Lambda Expression修改 Lambda 表达式
【发布时间】:2011-01-20 16:13:49
【问题描述】:

我正在使用 NHibernate 3.0 开发应用程序。我已经开发了一个 Repository hat 接受一个表达式来使用 QueryOver 进行一些过滤。我的方法是这样的:

public IEnumerable<T> FindAll(Expression<Func<T, bool>> filter) {
   return Session.QueryOver<T>().Where(filter).List();
}

它工作正常。所以,我也有一个服务层,我在这个服务中的方法接受原始类型,如下所示:

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);

【问题讨论】:

  • 我知道一种方法可以做到这一点 - 但我需要一点时间来实施。但是您可以只做一个x=&gt;(!string.IsNullOrEmpty(name)||name==x.Name)&amp;&amp;(stock.HasValue||x.Stock==stock??0) ... etc 我可以为您添加的是一种用常量替换 cloture 的方法,然后简化逻辑评估,以便表达式最终尽可能短。
  • 嗨,尼尔,如果可以的话,如果你能帮助我,我想看看一些代码 =D。我想象过你说的这种方式,我会研究这种可能性。谢谢!
  • @Felipe 看看我的回答 - 你去吧。
  • 好的,我认为您提出的解决方案会有问题。问题是一旦你调用 Compile() 和 Invoke() 你就会失去 nhibernate 依赖的元数据来构建查询。本质上,您将获得只能在客户端上评估的东西,而不是可以转换为 SQL 的东西。
  • 谢谢尼尔,我会选择你的解决方案。谢谢=D

标签: c# linq nhibernate lambda expression


【解决方案1】:

这是一种方法。我不会对您正在做的事情进行社论 - 它看起来像是通过示例查询,这几乎总是有问题的。就像这里的其他人最好避免的那样。不过表达的东西很有趣——所以我认为值得一试。

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;
}

}

【讨论】:

  • 嗨,尼尔,非常好的解决方案,我会和我的团队一起检查是否可行。但是我想知道您对我在第一篇文章中写的解决方案的看法,看看它是否是一个好的解决方案并给我您的意见?!谢谢大佬!
  • 我的评论附在你的问题上。
【解决方案2】:

首先,我会通过避免它来解决您的问题。我会有不同的方法。

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在必要时添加一些条件(当我的参数有值时)?

其次,是的,你想做的事情是可能的,但这不是我解决问题的方式。

【讨论】:

  • 嗨 Jason,谢谢,但在我的演示文稿中,当我需要调用服务时,我需要检查每个参数吗? (在第一篇文章中查看我的编辑)。我想要一个方法并传递参数和它......我有一些时刻我将有 10 个参数用于过滤器,并且它可以组合......为此我问是否可以做一个动态表达...谢谢!
【解决方案3】:

您的存储库方法定义建议您将 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();

【讨论】:

  • 这也是一个很好的解决方案,但我更愿意将此责任保留在我的存储库中。
【解决方案4】:

所以这就是你如何实际和 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 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多