實例講解Linq動態條件查詢
Linq動態條件目前已經應用的比較廣泛,但是熟練掌握其方法的人還不是很多,所以大多數開發者都有或多或少的疑問。今天筆者就來用實例為大家解決這些疑問。
在開發項目的過程中,我們經常會遇到這樣的需求,動態組合條件的查詢。比如淘寶中的高級搜索:
實例講解Linq動態條件查詢
要實現這個功能,通常的做法是拼接SQL查詢字符串,不管是放在程序中或是在存儲過程中。現在出現了Linq,下面來看看Linq動態條件查詢是怎樣實現的。
還是以Northwind數據庫為例,如果要查詢所有CustomerID以A或者B字母開頭的Customer,一般我們會這樣寫:
- var results = ctx.Customers.Where(c => c.CustomerID.StartsWith("A") ||
- c.CustomerID.StartsWith("B"));
如果需求改變,還要查詢出以X字母或者Y字母開頭的Customer,那可以增加查詢條件:
- var results = ctx.Customers.Where(c => c.CustomerID.StartsWith("A") ||
- c.CustomerID.StartsWith("B")
- || c.CustomerID.StartsWith("X") || c.CustomerID.StartsWith("Y"));
不過如果該需求不確定呢?我們不知道具體是哪些字母,可能傳過來的是一個字符串數組:
- string[] starts = ....
- var results = ctx.Customers.Where(c => ?);
我們可能很自然的這樣寫,雖然很清楚要做什么,但是很可惜編譯不通過,編譯器并不允許我們像這樣來組合條件。
- Expression
bool>> condition = cus => true; - foreach (string s in starts)
- {
- condition = cus => cus.CustomerID.StartsWith(s) || condition(cus);
- }
在Linq動態條件中提供一些方法允許我們動態構造Lambda表達式。如Expression.Call, Expression.Or, Expression.And,這樣代碼就可以寫成:
- ParameterExpression c = Expression.Parameter(typeof(Customer), "c");
- Expression condition = Expression.Constant(false);
- foreach (string s in starts)
- {
- Expression con = Expression.Call(
- Expression.Property(c, typeof(Customer).GetProperty("CustomerID")),
- typeof(string).GetMethod("StartsWith",
- new Type[] { typeof(string) }),
- Expression.Constant(s));
- condition = Expression.Or(con, condition);
- }
- Expression
bool>> end = - Expression.Lambda
bool>> - (condition, new ParameterExpression[] { c });
現在來解釋Linq動態條件這段代碼,首先構造了一個ParameterExpression對象,它作為參數傳到Lambda表達中(相當于c => c.CustomerID.StartsWith("A")這里的c)。然后用值為false的Expression用來初始化該表達式(Expression.Constant(false))。
- Expression con = Expression.Call(
- Expression.Property(c, typeof(Customer).GetProperty("CustomerID")),
- typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }),
- Expression.Constant(s));
- condition = Expression.Or(con, condition);
上面這段代碼是重頭戲,用Expression.Call方法動態構造一個表達式,其中Expression.Property(c, typeof(Customer).GetProperty("CustomerID"))轉換為c.CustomerID,typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) })表示string的StartsWith(string)方法,Expression.Constant(s)表示字符串常量,這個方法可以表示成:c.CustomerID.StartsWith(s)。然后調用Expression.Or方法組合各個條件(根據邏輯關系不同調用不同的方法,如or,and...)。
最后構造成Lambda表達式,現在就可以使用它了 ctx.Customers.Where(end)。
對于Linq動態條件查詢中,這個并不是最好的解決方法,使用這種方式生成的Lambda表達式,由于用到了反射,這樣編譯器不能檢查錯誤,很可能因為一個字母寫錯導致運行時拋出異常。因此,要用一個更好的方案,既能滿足我們的要求,又能讓編譯器更好的支持,這個方法筆者還未實現,就請你和筆者一起努力吧。
【編輯推薦】