1

我有一个应用程序,我正在尝试实现 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 字符串查询之前有什么办法吗?呵呵呵呵

谢谢!

4

1 回答 1

3

在这里,使用 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);
}

PredicateBuilder 来源:

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

于 2012-06-05T12:28:27.900 回答