动态Where条件与Queryover [英] Dynamic Where condition with Queryover
问题描述
我有一个应用程序,我想实现DDD概念。我有我的库类的一些方法来列出实体。我想知道我该怎么办查询与QueryOver进行过滤和
运营商,当参数被填满,样品
I have an application and I'm trying to implement DDD concepts. I have my repository class with some method to list entities. I would like to know how can I do a query with QueryOver to filter separating with AND
operator, when the parameter is filled, sample
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查询字符串?呵呵呵
Is there any way to do that before I use HQL string query? hehehe
感谢您!
推荐答案
下面,使用predicateBuilder:
Here, use 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来源:
PredicateBuilder Source:
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 /总而言之/ linqkit.aspx
For more information on PredicateBuilder and LinqKit go here: http://www.albahari.com/nutshell/linqkit.aspx
这篇关于动态Where条件与Queryover的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!