詳解LINQ+Ajax組合拳 用好泛型通用動(dòng)態(tài)查詢
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)代碼
- //===============//后臺(tái)任一 類型 列表//========================
- function AjaxForList(duixiang, pageid) {
- var searchWords = $("#SearchWords").val();
- var searchType = $("#SearchType").val();
- var channelId = $("#list").val();
- var IsRecycle = $("#IsRecycle").attr("checked"); //排序名
- var sortName = "CreaterData";
- //==================IsRecycle var Del = new Array();
- Del.push("=");
- //alert(IsRecycle);
- if (IsRecycle) { Del.push(1);
- }
- else { Del.push(0); }
- //==================FullTitle
- // 2010-3-22 0:00:00 var FullTitle = new Array();
- FullTitle.push("like");
- FullTitle.push("1");
- //==================FullTitle
- var Author = new Array();
- Author.push("like");
- Author.push("1");
- //==================IsAudit
- var IsAudit = new Array();
- IsAudit.push("=");
- IsAudit.push("0");
- //============================ $.ajax(
- // { type: "POST",
- url: "/Admin/UserKJ/AjaxForList",
- data: "ModelName=" + duixiang + "&&PageId=" + pageid
- + "&&sortName=" + sortName + "&&Del=" +
- Del + "&&FullTitle=" + FullTitle + "&&Author=" + Author + "&&IsAudit=" + IsAudit,
- dataType: "html",
- beforeSend: function(XMLHttpRequest) {
- // $(".PagerModeList").html(" ========LODING !!============");
- }, success: function(html) {
- //if (m != null)
- // alert(html);
- $(".PagerModeList").html(html);
- },
- complete: function(XMLHttpRequest, textStatus) {
- //HideLoading();
- },
- error: function() {
- //請(qǐng)求出錯(cuò)處理
- $(".PagerModeList").html("加載失敗");
- } }
- )
- //end $.ajax};
- // end AjaxRequest()
- {
2后臺(tái)接收:
使用 自定義的 兩個(gè) 字典 合并成 一個(gè) key-action-value 的字典
代碼
- public class SearchPage {
- public string ModelName { set; get; }
- public int PageId { set; get; }
- public string sortName { get; set; }
- /// <summary>
- /// RequestFormDictionary
- /// </summary>
- public ThreeDictionary<string, string, string>
- RFD = new ThreeDictionary<string, string, string>();
- public SearchPage()
- {
- RFD = new ThreeDictionary<string, string, string>();
- }
- public void InitDictionary(System.Web.HttpRequestBase httpRequestBase)
- {
- var requestForm = httpRequestBase.Form;
- foreach (var collection in requestForm.AllKeys)// x= Article,0,,1,0,false o=xx,xx;
- {
- string actionAndvalue = requestForm.Get(collection);
- if (string.IsNullOrEmpty(collection)) continue;//把參數(shù)分離
- List<string> templist = actionAndvalue.splitString(',');
- if (templist.Count() < 2) continue;
- RFD.Add(collection, templist[0], templist[1]);
- }
- }
- public string Dictionary2SQL()
- { StringBuilder stringBuilder = new StringBuilder();
- int count = 0;
- foreach (var keyActon in RFD.keyActons) {
- if (keyActon.Value == "Value") continue;
- // @1特別指定 如果 是 動(dòng)作是 Value 則 表示 直接意思
- string value = RFD.keyValues[keyActon.Key];
- if (count != 0) stringBuilder.Append(" and ");
- count++;
- if (keyActon.Value == "like") {
- // continue;
- //FullTitle.Contains(\"11\")
- stringBuilder.Append(string.Format(" {0}.Contains(\"{2}\") ", keyActon.Key, keyActon.Value, value));
- continue;
- }
- stringBuilder.Append(string.Format(" {0} {1} {2} ", keyActon.Key, keyActon.Value, value));
- }
- return stringBuilder.ToString();
- }
- }
3.根據(jù) 對(duì)象名 調(diào)用 對(duì)象 并過(guò)濾
代碼
- private readonly Repository2.IRepositoryResolver IRR;
- public UserKJController() {
- IRR = CMSContainer.GetContainer()[typeof(IRepositoryResolver)] as IRepositoryResolver;
- }
不知道的話 文末 會(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 也是支持 搜索的
- // continue;
- FullTitle.Contains(\"11\")
- stringBuilder.Append(string.Format(" {0}.Contains(\"{2}\") ",
- keyActon.Key, keyActon.Value, value));
原文標(biāo)題:泛型通用動(dòng)態(tài)查詢(LinQ+Ajax)
鏈接:http://www.cnblogs.com/facingwaller/archive/2010/05/16/1736634.html
【編輯推薦】
- Linq匿名類型簡(jiǎn)單概述
- Linq隨機(jī)讀取數(shù)據(jù)淺析
- Linq Lambda表達(dá)式全面分析
- Linq擴(kuò)展方法簡(jiǎn)單分析
- 初探Linq局部變量類型