具有查询结束的动态位置条件

本文关键字:动态 位置 条件 结束 查询 | 更新日期: 2023-09-27 18:36:25

我有一个应用程序,我正在尝试实现DDD概念。我有我的存储库类,其中包含一些列出实体的方法。我想知道如何使用 QueryOver 进行查询以使用运算符过滤分离AND当参数被填充时,示例

public IEnumerable<Product> FindProducts(string name, decimal? price, DateTime? validDate, int? stock, int? idSupplier)
{
   var query = Session.QueryOver<Product>().OrderBy(x => x.Name).Asc;
   if (!string.IsNullOrEmpty(name))
      // add where condition for name parameter
   if (price.HasValue)
      // add 'AND' where condition for price parameter
   if (validDate.HasValue)
      // add 'AND' where condition for validDate parameter
   if (idSupplier.HasValue)
      // add 'AND' where condition for idSupplier parameter
   // other possible conditions
   return query.List();
}

在使用 HQL 字符串查询之前有什么方法可以做到这一点吗? 嘿嘿嘿

谢谢!

具有查询结束的动态位置条件

在这里,使用 PredicateBuilder:

如何:

IQueryable<Product> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.False<Product>();
  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}

谓词生成器源:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
public static class PredicateBuilder
{
  public static Expression<Func<T, bool>> True<T> ()  { return f => true;  }
  public static Expression<Func<T, bool>> False<T> () { return f => false; }
  public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                      Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  }
  public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

有关 PredicateBuilder 和 LinqKit 的详细信息,请访问此处:http://www.albahari.com/nutshell/linqkit.aspx