今天公司有個(gè)項(xiàng)目需要到多個(gè)條件查詢的功能,以前兩三個(gè)條件的時(shí)候就用if去判斷,草草了事,由于這次有5-9個(gè)條件不等的情況下,總不能都用if吧,雖說能實(shí)現(xiàn),不過這代碼看上去也太難看,最重要的是沒有重用性,也不方便修改,網(wǎng)上找了下,五花八門的,要費(fèi)時(shí)間去理解它,還不如自己封裝下,也便于以后的使用:
我前端用的是BUI來設(shè)計(jì)的,所以條件的傳遞方式是get/post,所以這個(gè)方法是針對(duì)“查詢條件來自get/post方式的”,如果是用服務(wù)器控件傳的,這種方式是不適合的哦
好了,首先,為了方便存儲(chǔ)每個(gè)字段的鍵值和比較關(guān)系,先建立一個(gè)Condition類,方便以后操作,代碼如下:
public class Condition { //字段名 public string paramName { get; set; } //字段值 public string paramValue { get; set; } //操作符 public ConditionOperate Operation { get; set; } // 查詢所用到的運(yùn)算操作符 public enum ConditionOperate : byte { Equal, // 等于 NotEqual, // 不等于 Like, // 模糊查詢 Lessthan, // 小于等于 GreaterThan, // 大于等于 Less, //小于 Greater //大于 } }
接著,創(chuàng)建一個(gè)拼接查詢條件的類:
public static class ConditionBuilder { public static string getWhere<T>(List<Condition> conditions) { //獲取類型 Type t = typeof(T); //獲取類型中的屬性集合 PRopertyInfo[] properties = t.GetProperties(); foreach (PropertyInfo p in properties) { string colName = p.Name; //這里參數(shù)是通過url地址欄來(get方式)的,所以用Request.QueryString,如果是post(方式),改做下面的Request.From就好 for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++) { string value = HttpContext.Current.Request.QueryString[i].ToString(); //如果字段存在并且不為空 if (colName == HttpContext.Current.Request.QueryString.GetKey(i).ToString() && !string.IsNullOrEmpty(value)) { Condition ct = new Condition(); ct.paramName = colName; ct.paramValue = value; ct.Operation = Condition.ConditionOperate.Equal; conditions.Add(ct); } } } // 數(shù)組元素的順序應(yīng)該與ConditionOperate枚舉值順序相同 string[] operateType = { " = ", " <> ", " Like ", " <= ", " >= ", " < ", " > " }; StringBuilder strWhere = new StringBuilder(); strWhere.Append(" 1=1 "); foreach (Condition item in conditions) { int index = (int)item.Operation; strWhere.Append(" and " + item.paramName + operateType[index] + "'" + item.paramValue + "'"); } return strWhere.ToString(); } }
這里,后臺(tái)直接調(diào)用
List<Condition> conditions = new List<Condition>(); string strWhere = ConditionBuilder.getWhere<Sends>(conditions);
當(dāng)然,有一些特殊字段需要做特殊處理的話,也可以在調(diào)用getWhere先處理下。最后的結(jié)果是:
訪問http://localhost:14073/Index/GetData?a=a1&b=b1&start=0&limit=10&pageIndex=0&field=SendsID&direction=ASC&Receiver=%E9%83%AD%E4%BC%9F&FromUserName=8&FromSchoolName=87&SmsContent=8&SmsType=1&SendStatus=1&StartTime=&EndTime=&_=1404199763638
得到:1=1 and FromUserName = '8' and FromSchoolName = '87' and SmsType = '1' and SmsContent = '8' and SendStatus = '1' and Receiver = '郭偉'
本人也是菜鳥,此方法只能用來處理普通的查詢,對(duì)于復(fù)雜條件查詢的還希望有高手賜教,如果大家有其他好的,也希望能分享下。當(dāng)然,此方法也不適用于linq和ef,
如果有做過linq和ef動(dòng)態(tài)條件查詢的朋友也希望分享下。謝謝!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注