2012-06-05 33 views
1

我有一個應用程序,我試圖實現DDD的概念。我有我的存儲庫類與一些方法列出實體。我想知道我該怎麼辦查詢與QueryOver過濾與AND操作,當參數被填滿,樣品Dynamic Query Queryover的條件

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查詢字符串? hehehe

謝謝!

回答

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

+0

是的,我知道我可以做第二種方式,我怎樣才能添加其他可能的條件它? –

+0

@felipeoriani閱讀了謂詞構建器,假設你對第三方庫很熟悉(很多人使用它,這是安全的;-),那麼我會使用它。 – Faraday

+0

偉大的代碼,我會嘗試,謝謝:))...我不知道這個庫,我在哪裏可以找到它?謝謝[] s –