天天看點

LINQ動态組合查詢

 最近在項目中用到了LINQ,在界面上有許多組合查詢條件,我是一個比較懶的人,呵呵,不想在資料查詢層寫許多方法。我自己嘗試寫了個Expression的LINQ動态查詢,目的是到達了,但是我在代碼的初始表達式為null,每次組合AND前都要判斷是否為空,為空則傳回右邊的表達式。今天在網上Google了一下,看到肖坤:Linq動态查詢與模糊查詢(帶源碼示例)中講到的《dynamic linq queries / dynamic where clause (part 2) 》,中老外寫的PredicateExtensions類。便用這個類修改了下自己的方案。不在是全表達式樹動态生成了。今天特地寫了一個基于Northwind的Demo拿來和大家分享:

效果貼圖:

LINQ動态組合查詢

   界面是用Telerik控件做的(控件對于我們背景開發人員來說就是少調樣式)。

其中其實很簡單,主要方法就兩個,一個事表達式樹組合,和資料綁定。資料綁定,有一個

Expression<Func<Orders, bool>> 的where查詢條件。

Controller類Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Linq.Expressions;  
  6. using System.Diagnostics;   
  7. public class OrderController  
  8. {  
  9.     protected NorthwindDataContext DataContext  
  10.     {  
  11.         get  
  12.         {  
  13.             NorthwindDataContext context =   
  14. HttpContext.Current.Items["NorthwindDataContext"]  
  15.  as NorthwindDataContext;  
  16.             if (context == null)  
  17.             {  
  18.                 context = new NorthwindDataContext();  
  19.                 HttpContext.Current.Items["NorthwindDataContext"] = context;  
  20.             }  
  21.             return context;  
  22.         }  
  23.     }  
  24.      public List<Orders> GetOrders<TKey>(int currentPage,  
  25.  int pagesize, Expression<Func<Orders, bool>> whereQuery,   
  26. QueryableOrderEntry<Orders, TKey> orderQuery)  
  27. //重點在這裡的參數   
  28.     {  
  29.         IQueryable<Orders> query = DataContext.Orders;  
  30.         if (whereQuery != null)  
  31.         {  
  32.             query = query.Where(whereQuery);  
  33.         }  
  34.         if (orderQuery != null)  
  35.         {  
  36.             if (orderQuery.OrderDirection == OrderDirection.ASC)  
  37.             {  
  38.                query= query.OrderBy(orderQuery.Expression);  
  39.             }  
  40.             else 
  41.             {  
  42.                 query = query.OrderByDescending(orderQuery.Expression);  
  43.             }  
  44.         }  
  45.         Debug.WriteLine(DataContext.GetCommand(query.Skip((currentPage - 1) * pagesize)  
  46.             .Take(pagesize)).CommandText);  
  47.         return query.Skip((currentPage - 1) * pagesize).Take(pagesize).ToList();  
  48.     }  
  49.     public void Save()  
  50.     {  
  51.         DataContext.SubmitChanges();  
  52.     }  
  53. }  
  54. 複制代碼  
我的排序輔助類:      
  1. 代碼  
  2. using System;  
  3. using System.Linq.Expressions;  
  4.     public class QueryableOrderEntry<TSource, TKey>  
  5.     {  
  6.         public QueryableOrderEntry(Expression<Func<TSource, TKey>> expression)  
  7.         {  
  8.             this.Expression = expression;  
  9.             OrderDirection = OrderDirection.ASC;  
  10.         }  
  11.         public QueryableOrderEntry(Expression<Func<TSource, TKey>> expression,   
  12.                   OrderDirection orderDirection)  
  13.         {  
  14.             this.Expression = expression;  
  15.             OrderDirection = orderDirection;  
  16.         }  
  17.         public Expression<Func<TSource, TKey>> Expression  
  18.         {  
  19.             get;  
  20.             set;  
  21.         }  
  22.         public OrderDirection OrderDirection  
  23.         {  
  24.             get;  
  25.             set;  
  26.         }  
  27.     }  
  28.     public enum OrderDirection  
  29.     {  
  30.         ASC, DESC 
  31.     }  
  32. 複制代碼  
老外的PredicateExtensions類很簡單,隻是真的思路很優秀,看到代碼我們都會恍然大悟,      
但是估計我這鼠輩很難想到。      

代碼

  1. public static class PredicateExtensions  
  2. {  
  3.     public static Expression<Func<T, bool>> True<T>() { return f => true; }  
  4.     public static Expression<Func<T, bool>> False<T>() { return f => false; }  
  5.     public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expression1,  
  6.             Expression<Func<T, bool>> expression2)  
  7.     {  
  8.         var invokedExpression = Expression.Invoke(expression2,   
  9. expression1.Parameters.Cast<Expression>());  
  10.         return Expression.Lambda<Func<T, bool>>(Expression.Or(  
  11. expression1.Body, invokedExpression),   
  12.            expression1.Parameters);  
  13.     }  
  14.     public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1,   
  15.             Expression<Func<T, bool>> expression2)  
  16.     {  
  17.         var invokedExpression = Expression.Invoke(expression2,   
  18. expression1.Parameters.Cast<Expression>());  
  19.         return Expression.Lambda<Func<T, bool>>(Expression.And(expression1.Body,   
  20.           invokedExpression), expression1.Parameters);  
  21.     }  
  22. }  
  23. 複制代碼  

上面貼圖條件輸出框中輸出的sql我也截了一個圖來供參考:

LINQ動态組合查詢
sql看不全:故在這裡也貼一個:      
  1. SELECT TOP (15) [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate],  
  2.  [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName],  
  3.  [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode],   
  4. [t0].[ShipCountry]FROM [dbo].[Orders] AS [t0]  
  5. WHERE ([t0].[CustomerID] LIKE @p0) AND ([t0].[EmployeeID] IS NOT NULL) AND   
  6. (([t0].[EmployeeID]) = @p1) AND ([t0].[OrderDate] IS NOT NULL) AND   
  7. (([t0].[OrderDate]) >= @p2) AND ([t0].[OrderDate] IS NOT NULL) AND   
  8. (([t0].[OrderDate]) <= @p3)ORDER BY [t0].[CustomerID] DESC 
  9. 複制代碼  
在這裡說老外的思想優秀,該講解一下,但是限于篇幅,還有時間淩晨1點了,故改到下回講解。      
附帶:      

本随筆代碼下載下傳

:代碼

代碼:

  1. using System;  
  2. using System.Web.UI;  
  3. using System.Linq.Expressions;  
  4.  public partial class _Default : System.Web.UI.Page  
  1. {  
  2.     private OrderController controller = new OrderController();  
  3.     protected void Page_Load(object sender, EventArgs e)  
  4.     {  
  5.         if (!IsPostBack)  
  6.         {  
  7.             Bindgrid(null);  
  8.         }  
  9.     }   
  10.     public void Bindgrid(Expression<Func<Orders, bool>> whereqQuery)  
  11.     {  
  12.         grid.DataSource = controller.GetOrders(1, 15, whereqQuery,  
  13.  new QueryableOrderEntry<Orders,   
  14. string>(t => t.CustomerID, OrderDirection.DESC));// 分頁數目應該用分頁控件,  
  15. 這裡隻是簡單測試,是以偷個懶  
  16.         grid.DataBind();  
  17.     }  
  18.      protected void btnSearch_Click(object sender, ImageClickEventArgs e)  
  19.     {  
  20.         Expression<Func<Orders, bool>> expression = PredicateExtensions.True<Orders>();  
  21.         if (!string.IsNullOrEmpty(txtCustomerId.Text.Trim()))  
  22.         {  
  23.             string str = txtCustomerId.Text.Trim();  
  24.             expression = expression.And(o => o.CustomerID.Contains(str));  
  25.         }  
  26.         if (!string.IsNullOrEmpty(txtEmplyeeId.Text.Trim()))  
  27.         {  
  28.             string str = txtEmplyeeId.Text.Trim();  
  29.             expression = expression.And(o => o.EmployeeID.HasValue &&   
  30.                 o.EmployeeID.Value.Equals(int.Parse(str)));  
  31.         }  
  32.         if (txtOrderDateStart.SelectedDate.HasValue)  
  33.         {DateTime dt=txtOrderDateStart.SelectedDate.Value;  
  34.             expression = expression.And(o => o.OrderDate.HasValue  
  35.  && o.OrderDate.Value >= dt);  
  36.         }  
  37.         if (txtOrderDateEnd.SelectedDate.HasValue)  
  38.         {  
  39.             DateTime dt = txtOrderDateEnd.SelectedDate.Value;  
  40.             expression = expression.And(o => o.OrderDate.HasValue  
  41.  && o.OrderDate.Value <=dt);  
  42.         }  
  43.         Bindgrid(expression);   
  44.     }  
  45. }  
  46. 複制代碼