實(shí)例講解Linq動(dòng)態(tài)條件查詢
Linq動(dòng)態(tài)條件目前已經(jīng)應(yīng)用的比較廣泛,但是熟練掌握其方法的人還不是很多,所以大多數(shù)開發(fā)者都有或多或少的疑問。今天筆者就來用實(shí)例為大家解決這些疑問。
在開發(fā)項(xiàng)目的過程中,我們經(jīng)常會(huì)遇到這樣的需求,動(dòng)態(tài)組合條件的查詢。比如淘寶中的高級(jí)搜索:
實(shí)例講解Linq動(dòng)態(tài)條件查詢
要實(shí)現(xiàn)這個(gè)功能,通常的做法是拼接SQL查詢字符串,不管是放在程序中或是在存儲(chǔ)過程中?,F(xiàn)在出現(xiàn)了Linq,下面來看看Linq動(dòng)態(tài)條件查詢是怎樣實(shí)現(xiàn)的。
還是以Northwind數(shù)據(jù)庫(kù)為例,如果要查詢所有CustomerID以A或者B字母開頭的Customer,一般我們會(huì)這樣寫:
- 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"));
不過如果該需求不確定呢?我們不知道具體是哪些字母,可能傳過來的是一個(gè)字符串?dāng)?shù)組:
- 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動(dòng)態(tài)條件中提供一些方法允許我們動(dòng)態(tài)構(gòu)造Lambda表達(dá)式。如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 });
現(xiàn)在來解釋Linq動(dòng)態(tài)條件這段代碼,首先構(gòu)造了一個(gè)ParameterExpression對(duì)象,它作為參數(shù)傳到Lambda表達(dá)中(相當(dāng)于c => c.CustomerID.StartsWith("A")這里的c)。然后用值為false的Expression用來初始化該表達(dá)式(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方法動(dòng)態(tài)構(gòu)造一個(gè)表達(dá)式,其中Expression.Property(c, typeof(Customer).GetProperty("CustomerID"))轉(zhuǎn)換為c.CustomerID,typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) })表示string的StartsWith(string)方法,Expression.Constant(s)表示字符串常量,這個(gè)方法可以表示成:c.CustomerID.StartsWith(s)。然后調(diào)用Expression.Or方法組合各個(gè)條件(根據(jù)邏輯關(guān)系不同調(diào)用不同的方法,如or,and...)。
最后構(gòu)造成Lambda表達(dá)式,現(xiàn)在就可以使用它了 ctx.Customers.Where(end)。
對(duì)于Linq動(dòng)態(tài)條件查詢中,這個(gè)并不是最好的解決方法,使用這種方式生成的Lambda表達(dá)式,由于用到了反射,這樣編譯器不能檢查錯(cuò)誤,很可能因?yàn)橐粋€(gè)字母寫錯(cuò)導(dǎo)致運(yùn)行時(shí)拋出異常。因此,要用一個(gè)更好的方案,既能滿足我們的要求,又能讓編譯器更好的支持,這個(gè)方法筆者還未實(shí)現(xiàn),就請(qǐng)你和筆者一起努力吧。
【編輯推薦】