具有Queryover的动态Where条件

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

 public IEnumerable FindProducts(string name, decimal? price, DateTime? validDate, int? stock, int? idSupplier) { var query = Session.QueryOver().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 SearchProducts (params string[] keywords) { var predicate = PredicateBuilder.False(); 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> True () { return f => true; } public static Expression> False () { return f => false; } public static Expression> Or (this Expression> expr1, Expression> expr2) { var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ()); return Expression.Lambda> (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters); } public static Expression> And (this Expression> expr1, Expression> expr2) { var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ()); return Expression.Lambda> (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters); } } 

有关PredicateBuilder和LinqKit的更多信息,请访问: http : //www.albahari.com/nutshell/linqkit.aspx