詳解LINQ+Ajax組合拳 用好泛型通用動態查詢
51CTO開發頻道向您推薦《LINQ教程-LINQ to SQL技術精解》專題,以便于進行對比。
我的春秋癡夢第二步:
寫一個 通用的 對象 列表 ,還 包含 搜索和 屬性過濾。
具體的效果是:
當新 業務 添加一個 表的時候,只需要在 對象模型里的 添加一個 model
后臺幾乎不需寫代碼。
(我是后臺:激動人心!)
調用的對象,第幾頁,屬性的 過濾 和搜索全是 前臺的Ajax參數控制
(我是前臺:#$!@#$%$^#$%# )
下面說說我的思路吧:
1.前臺發出請求 寫明 調用的 modleName 和 一些屬性 的過濾
如:Author like,1 ModelName Article 搜索作者 包含 1 對象名 文章
2.后臺接受 處理傳遞的參數
3.根據 對象名 調用 對象 并過濾
4.根據 對象名 返回 對應 頁面
1.前臺JS 代碼
前臺代碼
- //===============//后臺任一 類型 列表//========================
- 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() {
- //請求出錯處理
- $(".PagerModeList").html("加載失敗");
- } }
- )
- //end $.ajax};
- // end AjaxRequest()
- {
2后臺接收:
使用 自定義的 兩個 字典 合并成 一個 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;//把參數分離
- 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特別指定 如果 是 動作是 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.根據 對象名 調用 對象 并過濾
代碼
- private readonly Repository2.IRepositoryResolver IRR;
- public UserKJController() {
- IRR = CMSContainer.GetContainer()[typeof(IRepositoryResolver)] as IRepositoryResolver;
- }
不知道的話 文末 會給出 鏈接。
AjaxForList
public ActionResult AjaxForList(SearchPage searchPage){
// Response.Write(DateTime.Now);
searchPage.InitDictionary(Request);//把 字符串裝進字典里面
IRepository ir = IRR.GetRepository(
searchPage.ModelName.str2type()); //根據類型得到要操作的類
var iq = ir.GetAll();// 得到所有
iq = iq.Order(searchPage.sortName); // 并 排序
iq = iq.Where(searchPage.Dictionary2SQL());//根據 字典 自動 過濾
PagerInfo pif = new PagerInfo(iq.Count(), searchPage.PageId); //頁信息
iq = iq.Skip(pif.PageSize * (pif.CurrentPage - 1)).Take(pif.PageSize); //分頁
PagerIndex<PagerInfo, IQueryable>
pagerIndex2 = new PagerIndex<PagerInfo, IQueryable>(pif, iq);//裝配
//Response.Write(DateTime.Now.ToLongTimeString());
return View("AjaxListFor" + searchPage.ModelName, pagerIndex2); //返回
}
這里 用到了 System.Linq.Dynamic;
來做核心 的 排序和過濾 。
然后放出一個 firebug的 圖
通過我自己代碼輸出耗費的時間 不用1s 而且還是我本機的破機子,1G的內存條郁悶要死。
比我原來預想的 泛型會很耗性能。 感覺好了很多。
這是我沒找到 Dynamic 之前 自己做的一個 輪子
辛辛苦苦做出來 還不支持 nullable的 類型 ,
想了辦法 二次調用 構造 了 c.WithPic.Value的表達式
{Table(KF_Articles).OrderBy(ArticleID => ArticleID.ArticleID).Where(item => (item.Del = 0)).Where(item => (item.WithPic.Value = 1))}
結果
跟重典兄討論一下,還是沒有結果。
等有時間再琢磨一下,希望 觀眾們 指點一下。
EqualValue我的輪子
//search/// <summary>
/// 某個屬性為某個值
/// </summary>
/// <param name="pif">屬性</param>
/// <param name="value">值</param>
/// <param name="action">動作: < = 等 </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 構造 參數 item 即 T
var itemParameter = Expression.Parameter(typeof(T), "item");
IQueryable<T> iqTemp = iq as IQueryable<T>;
// 轉換成 model 的 那種類型
// 判斷是否是 Nullable 的 如果是 的話 就 把類型轉換成對應的 非 nullable 的
Type tempType = typeof(T).GetProperty(pifName).PropertyType;
if (tempType.FullName.Contains("Nullable"))
{//組建一個表達式樹來創建一個參數
}
var tempType2 = tempType.Nullable2Not();
value = Convert.ChangeType(value, tempType2);
//取出他的值
var left = Expression.Property(// 左邊的參數
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");
//組建表達式樹: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>>//構造表達式
(ep, new[] { itemParameter });
return iqTemp.Where(whereExpression);
指出 肖坤 兄的一處小錯,Dynamic 也是支持 搜索的
- // continue;
- FullTitle.Contains(\"11\")
- stringBuilder.Append(string.Format(" {0}.Contains(\"{2}\") ",
- keyActon.Key, keyActon.Value, value));
原文標題:泛型通用動態查詢(LinQ+Ajax)
鏈接:http://www.cnblogs.com/facingwaller/archive/2010/05/16/1736634.html
【編輯推薦】