查詢排序 EF中的Lambda查詢 排序 高效分頁

2021-10-14 17:54:18 字數 1948 閱讀 6321

ef中的lambda查詢、排序、高效分頁

資料庫中有張classinfo的表,如果列印classid為4的classname,方法如下。

方法1、使用普通方法。

1 protected void button1_click(object sender, eventargs e) 2 10 }
方法2、使用iqueryable的擴充套件方法where。

擴充套件方法是:本來就沒有這個方法,後來經常能操作使用,額外地擴充套件了乙個方法。下面是where擴充套件方法的定義。

public static iqueryable where(this iqueryable source, expression> predicate);

其中this iqueryable source 不是要求要傳入的引數,這表明這個擴充套件方法"where"是給哪個型別擴充套件的。

需要傳入的引數有:

where:

tsource:方法的資料來源型別,如classinfo。

expression

引數是傳乙個委託,可以寫乙個符合這個委託的匿名函式或著lambda表示式。這個委託型別的運算結果是bool型別(而不是傳乙個bool型別),

如果篩選條件為true就把篩選結果給了iqueryable,如果篩選結果為false,那麼iqueryable結果中就為null。

1 protected void button1_click(object sender, eventargs e) 2
方法1和方法2執行的效率都是一樣的,ef根據寫的linq表示式或者lambda生成相應的sql語句。

普通公升序、降序寫法。

1 protected void button1_click(object sender, eventargs e) 2 13 14 //普通降序寫法。15 codefirstdbcontext db = new codefirstdbcontext();16 var classinfolist = from c in db.classinfo17 where c.classid > 018 orderby c.classid descending19 select c;20 foreach (classinfo cc in classinfolist)21 24 }
擴充套件方法公升序、降序。

1 protected void button1_click(object sender, eventargs e) 2  18 19 //也可以對字串進行排序20 codefirstdbcontext db = new codefirstdbcontext();21 iqueryable classinfolist = db.classinfo.where(c => true).orderby(c => c.classname);22 foreach (classinfo classinfo in classinfolist)23 26 }
分頁。用到了iquerable的兩個方法skip():跳過、take()取。

1 protected void button1_click(object sender, eventargs e) 2 16 17 //第二種寫法。18 codefirstdbcontext db = new codefirstdbcontext();19 iqueryable classinfolist = db.classinfo.where(c => true).orderby(c => c.classid).skip((pageindex - 1) * pagesize).take(pagesize);20 foreach (classinfo classinfo in classinfolist)21 24 }

EF實現分頁查詢 條件查詢 排序

先來看看幾個linq to sql的幾個函式。take 說明 獲取集合的前n個元素 延遲。即只返回限定數量的結果集。var q from e in db.employees orderby e.hiredate select e take 5 語句描述 選擇所雇用的前5個雇員。skip 說明 跳過集...

EF提供的3中查詢方式

1.linq to entities using testentities te new testentities lambda方式 using testentities te new testentities 2.query builder mothed using testentities te...

EF中巢狀類的where查詢

有乙個訂單類 order,在訂單order類中有乙個子類,訂單詳細類orderdetail。需求 根據訂單詳細類的字段過濾資料 public class order public orderdetail orderdetail public class orderdetail public stri...