自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

詳解LINQ+Ajax組合拳 用好泛型通用動(dòng)態(tài)查詢

開(kāi)發(fā) 后端
本文將介紹LINQ+Ajax組合,這樣的組合有利于用好泛型通用動(dòng)態(tài)查詢。查詢還包括搜索和屬性過(guò)濾。

51CTO開(kāi)發(fā)頻道向您推薦《LINQ教程-LINQ to SQL技術(shù)精解》專題,以便于進(jìn)行對(duì)比。

我的春秋癡夢(mèng)第二步:

寫一個(gè) 通用的 對(duì)象 列表 ,還 包含 搜索和 屬性過(guò)濾。

具體的效果是:

當(dāng)新 業(yè)務(wù) 添加一個(gè) 表的時(shí)候,只需要在 對(duì)象模型里的 添加一個(gè) model

后臺(tái)幾乎不需寫代碼。

(我是后臺(tái):激動(dòng)人心!)

調(diào)用的對(duì)象,第幾頁(yè),屬性的 過(guò)濾 和搜索全是 前臺(tái)的Ajax參數(shù)控制

(我是前臺(tái):#$!@#$%$^#$%# )

下面說(shuō)說(shuō)我的思路吧:

1.前臺(tái)發(fā)出請(qǐng)求 寫明 調(diào)用的 modleName 和 一些屬性 的過(guò)濾 

如:Author like,1 ModelName Article   搜索作者 包含 1   對(duì)象名 文章

2.后臺(tái)接受 處理傳遞的參數(shù)

3.根據(jù) 對(duì)象名 調(diào)用 對(duì)象 并過(guò)濾

4.根據(jù) 對(duì)象名 返回 對(duì)應(yīng) 頁(yè)面

 1.前臺(tái)JS 代碼

前臺(tái)代碼

  1. //===============//后臺(tái)任一 類型  列表//========================
  2. function AjaxForList(duixiang, pageid) {      
  3. var searchWords = $("#SearchWords").val();      
  4. var searchType = $("#SearchType").val();      
  5. var channelId = $("#list").val();      
  6. var IsRecycle = $("#IsRecycle").attr("checked");    //排序名      
  7. var sortName = "CreaterData";      
  8. //==================IsRecycle    var Del = new Array();      
  9. Del.push("=");   
  10. //alert(IsRecycle);      
  11. if (IsRecycle) { Del.push(1);   
  12. }      
  13. else { Del.push(0); }      
  14. //==================FullTitle      
  15. // 2010-3-22 0:00:00    var FullTitle = new Array();      
  16. FullTitle.push("like");      
  17. FullTitle.push("1");      
  18. //==================FullTitle      
  19. var Author = new Array();     
  20.  Author.push("like");     
  21.  Author.push("1");      
  22. //==================IsAudit          
  23.  var IsAudit = new Array();     
  24.  IsAudit.push("=");     
  25.  IsAudit.push("0");     
  26.  //============================    $.ajax(
  27. //        {        type: "POST",        
  28. url: "/Admin/UserKJ/AjaxForList",       
  29. data: "ModelName=" + duixiang + "&&PageId=" + pageid 
  30. + "&&sortName=" + sortName + "&&Del=" + 
  31. Del + "&&FullTitle=" + FullTitle + "&&Author=" + Author + "&&IsAudit=" + IsAudit,  
  32.       dataType: "html", 
  33.        beforeSend: function(XMLHttpRequest) {   
  34. //            $(".PagerModeList").html(" ========LODING !!============");      
  35.   },        success: function(html) {             
  36.  //if (m != null)             
  37.  //  alert(html);             
  38.  $(".PagerModeList").html(html);                    
  39.  },         
  40.  complete: function(XMLHttpRequest, textStatus) {             
  41.  //HideLoading();       
  42.    },          
  43. error: function() {              
  44. //請(qǐng)求出錯(cuò)處理              
  45. $(".PagerModeList").html("加載失敗");         
  46.  }    }                               
  47.   )  
  48. //end $.ajax};   
  49. // end  AjaxRequest()   
 

 2后臺(tái)接收:

 使用 自定義的 兩個(gè) 字典 合并成 一個(gè) key-action-value 的字典

代碼

  1. public class SearchPage    {         
  2.  public string ModelName { setget; }         
  3.  public int PageId { setget; }         
  4.  public string sortName { getset; }        
  5.   /// <summary>         
  6.  /// RequestFormDictionary        
  7.   /// </summary>         
  8.  public ThreeDictionary<stringstringstring
  9. RFD = new ThreeDictionary<stringstringstring>();     
  10.    public SearchPage()        
  11.   {             
  12.  RFD = new ThreeDictionary<stringstringstring>();        
  13.   }       
  14.    public void InitDictionary(System.Web.HttpRequestBase httpRequestBase)        
  15.   {           
  16.    var requestForm = httpRequestBase.Form;   
  17.     foreach (var collection in requestForm.AllKeys)// x=     Article,0,,1,0,false  o=xx,xx;            
  18.   {                
  19.   string actionAndvalue = requestForm.Get(collection);                
  20.   if (string.IsNullOrEmpty(collection)) continue;//把參數(shù)分離                   
  21.  List<string> templist = actionAndvalue.splitString(',');                 
  22.  if (templist.Count() < 2) continue;             
  23.    RFD.Add(collection, templist[0], templist[1]);              
  24. }          
  25. }         
  26.  public string Dictionary2SQL()        
  27.   {            StringBuilder stringBuilder = new StringBuilder();            
  28.   int count = 0;            
  29.   foreach (var keyActon in RFD.keyActons)            {                  
  30. if (keyActon.Value == "Value"continue;  
  31.  // @1特別指定 如果 是 動(dòng)作是 Value  則 表示 直接意思                 
  32.  string value = RFD.keyValues[keyActon.Key];                 
  33.  if (count != 0) stringBuilder.Append(" and  ");                 
  34.  count++;                 
  35.  if (keyActon.Value == "like")                {                     
  36.  //     continue;    
  37.   //FullTitle.Contains(\"11\")                 
  38. stringBuilder.Append(string.Format(" {0}.Contains(\"{2}\") ", keyActon.Key, keyActon.Value, value));                 
  39.  continue;                 
  40.  }               
  41.    stringBuilder.Append(string.Format(" {0} {1} {2} ", keyActon.Key, keyActon.Value, value));        
  42.       }         
  43.      return stringBuilder.ToString();      
  44.     }          
  45.      } 
 

3.根據(jù) 對(duì)象名 調(diào)用 對(duì)象 并過(guò)濾

代碼

  1. private readonly Repository2.IRepositoryResolver IRR;          
  2. public UserKJController()        {                         
  3.  IRR = CMSContainer.GetContainer()[typeof(IRepositoryResolver)] as IRepositoryResolver;   
  4.        } 
這里用到了 一個(gè) CASTLE  和 一個(gè) Repository 相信 能看到這里的 應(yīng)該都知道這些吧。

不知道的話 文末 會(huì)給出 鏈接。

AjaxForList

public ActionResult AjaxForList(SearchPage searchPage)

{

// Response.Write(DateTime.Now);

searchPage.InitDictionary(Request);//把 字符串裝進(jìn)字典里面

IRepository ir = IRR.GetRepository(

searchPage.ModelName.str2type()); //根據(jù)類型得到要操作的類

var iq = ir.GetAll();// 得到所有

iq = iq.Order(searchPage.sortName); // 并 排序

 

iq = iq.Where(searchPage.Dictionary2SQL());//根據(jù) 字典 自動(dòng) 過(guò)濾

PagerInfo pif = new PagerInfo(iq.Count(), searchPage.PageId); //頁(yè)信息

iq = iq.Skip(pif.PageSize * (pif.CurrentPage - 1)).Take(pif.PageSize); //分頁(yè)

PagerIndex<PagerInfo, IQueryable>

pagerIndex2 = new PagerIndex<PagerInfo, IQueryable>(pif, iq);//裝配

//Response.Write(DateTime.Now.ToLongTimeString());

return View("AjaxListFor" + searchPage.ModelName, pagerIndex2); //返回

}

這里 用到了  System.Linq.Dynamic;

來(lái)做核心 的 排序和過(guò)濾 。

然后放出一個(gè) firebug的 圖

 

 通過(guò)我自己代碼輸出耗費(fèi)的時(shí)間 不用1s 而且還是我本機(jī)的破機(jī)子,1G的內(nèi)存條郁悶要死。

比我原來(lái)預(yù)想的 泛型會(huì)很耗性能。 感覺(jué)好了很多。

 這是我沒(méi)找到  Dynamic 之前 自己做的一個(gè) 輪子

辛辛苦苦做出來(lái) 還不支持 nullable的 類型 ,

想了辦法 二次調(diào)用 構(gòu)造 了 c.WithPic.Value的表達(dá)式

{Table(KF_Articles).OrderBy(ArticleID => ArticleID.ArticleID).Where(item => (item.Del =  0)).Where(item => (item.WithPic.Value = 1))}

 結(jié)果

 

跟重典兄討論一下,還是沒(méi)有結(jié)果。

等有時(shí)間再琢磨一下,希望 觀眾們 指點(diǎn)一下。

EqualValue我的輪子

//search

/// <summary>

/// 某個(gè)屬性為某個(gè)值

/// </summary>

/// <param name="pif">屬性</param>

/// <param name="value">值</param>

/// <param name="action">動(dòng)作: < = 等 </param>

/// <returns></returns>

public IQueryable EqualValue(string pifName, object value, ActionType action, IQueryable iq)

{

 

if (iq == null) throw new Exception(" IQueryable iq 為空");

if (typeof(T).GetProperty(pifName) == null)

throw new Exception(pifName + " in " + typeof(T).Name);

 

//1 構(gòu)造 參數(shù) item 即 T

var itemParameter = Expression.Parameter(typeof(T), "item");

IQueryable<T> iqTemp = iq as IQueryable<T>;

// 轉(zhuǎn)換成 model 的 那種類型

// 判斷是否是 Nullable 的 如果是 的話 就 把類型轉(zhuǎn)換成對(duì)應(yīng)的 非 nullable 的

Type tempType = typeof(T).GetProperty(pifName).PropertyType;

if (tempType.FullName.Contains("Nullable"))

{//組建一個(gè)表達(dá)式樹(shù)來(lái)創(chuàng)建一個(gè)參數(shù)

 

}

var tempType2 = tempType.Nullable2Not();

value = Convert.ChangeType(value, tempType2);

//取出他的值

var left = Expression.Property(// 左邊的參數(shù)

itemParameter,

pifName // 屬性的 名字

);

 

var right = Expression.Constant(value);//Constant 常量 右邊的值

 

#region //=========================各種 action 操作

BinaryExpression ep;

if (action == ActionType.Equal)

{

if (tempType.FullName.Contains("Nullable"))

{

ParameterExpression param =

Expression.Parameter(typeof(T), "item");// item2

//item2.pifName => item2.WithPic

// item2.WithPic.value

MemberExpression param11 = Expression.Property(param, pifName);

MemberExpression param12 = Expression.Property(param11, "Value");

// typeof(T).GetProperty(pifName).GetType().GetProperty("Value"));

// ParameterExpression param2 =

//Expression.Parameter(typeof(T).GetProperty(pifName).GetType(), "Value");

//組建表達(dá)式樹(shù):c.ContactName

ep = Expression.Equal(param12, right);

}

else

{

ep = Expression.Equal(left, right);

}

 

 

}

else if (action == ActionType.GreaterThan)

{

ep = Expression.GreaterThan(left, right);

}

else if (action == ActionType.GreaterThanOrEqual)

{

ep = Expression.GreaterThanOrEqual(left, right);

}

else if (action == ActionType.LessThan)

{

ep = Expression.LessThan(left, right);

}

else if (action == ActionType.LessThanOrEqual)

{

ep = Expression.LessThanOrEqual(left, right);

}

else if (action == ActionType.NotEqual)

{

ep = Expression.NotEqual(left, right);

}

else

{

 

throw new Exception(action + " not find!");

}

 

#endregion

var whereExpression = Expression.Lambda<Func<T, bool>>//構(gòu)造表達(dá)式

(ep, new[] { itemParameter });

 

 

return iqTemp.Where(whereExpression);

指出 肖坤 兄的一處小錯(cuò),Dynamic 也是支持 搜索的

  1. //     continue;      
  2. FullTitle.Contains(\"11\")                    
  3. stringBuilder.Append(string.Format(" {0}.Contains(\"{2}\") "
  4. keyActon.Key, keyActon.Value, value));  

 

原文標(biāo)題:泛型通用動(dòng)態(tài)查詢(LinQ+Ajax)

鏈接:http://www.cnblogs.com/facingwaller/archive/2010/05/16/1736634.html

【編輯推薦】

  1. Linq匿名類型簡(jiǎn)單概述
  2. Linq隨機(jī)讀取數(shù)據(jù)淺析
  3. Linq Lambda表達(dá)式全面分析
  4. Linq擴(kuò)展方法簡(jiǎn)單分析
  5. 初探Linq局部變量類型

 

責(zé)任編輯:彭凡 來(lái)源: 博客園
相關(guān)推薦

2009-05-27 10:12:27

LINQ泛型字典Dictionary

2009-09-08 16:36:10

LINQ查詢基于泛型類

2009-04-24 09:33:12

LINQ查詢非泛型

2009-09-14 18:57:19

LINQ查詢

2009-09-14 14:01:21

LINQ泛型數(shù)據(jù)集

2009-09-08 17:27:18

LINQ to Dat

2009-09-17 16:46:34

Linq to sql

2009-09-15 10:16:01

LINQ動(dòng)態(tài)查詢

2009-09-18 15:15:12

LINQ to SQL

2009-09-15 09:19:22

linq動(dòng)態(tài)條件

2009-09-07 22:29:04

LINQ組合查詢

2021-06-18 08:25:42

Java泛型通配符

2009-09-17 16:20:43

Linq to sql

2009-09-15 09:45:23

Linq動(dòng)態(tài)條件

2009-09-17 17:03:13

LINQ動(dòng)態(tài)查詢

2009-09-14 19:14:51

LINQ動(dòng)態(tài)查詢

2024-10-28 00:40:49

Go語(yǔ)法版本

2011-04-13 09:16:55

泛型

2009-09-14 14:49:12

LINQ查詢基礎(chǔ)知識(shí)

2009-09-07 22:54:03

Linq組合查詢
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)