转:ADO.Net Entity Framework : (七) 多條件查詢

在設計表單的時候,我們常常會讓使用者去選擇要輸入哪些資料, 
然後把條件組合起來去查詢資料,這邊示範兩種利用EntityFramework的多條件查詢寫法

第一種 是利用StingBuilder把字串加起來,這應該也是大家最常用的寫法, 
不過這方法要自己知道欄位名稱,也無法在設計階段就知道有沒有錯誤, 
當然也沒有IntellSence

01 ////示範:多條件查詢
02 using (TestEntities te = new TestEntities())
03 {
04     ////寫法一
05     StringBuilder sb = new StringBuilder();
06                  
07     if (!string.IsNullOrEmpty(TextBoxId.Text))
08     {
09         sb.Append(" and it.user_id = " + TextBoxId.Text);               
10     }
11                  
12     if (!string.IsNullOrEmpty(TextBoxName.Text))
13     {
14         sb.Append(" and it.user_name = '" + TextBoxName.Text + "'");
15     }
16  
17     if (!string.IsNullOrEmpty(TextBoxAddress.Text))
18     {
19         sb.Append(" and it.user_address = '" + TextBoxAddress.Text + "'");
20     }
21  
22     List<user> users;
23  
24     ////取得資料
25     if (sb.Length != 0)
26     {               
27         users = te.user.Where(sb.ToString().Substring(4)).ToList();
28     }
29     else
30     {
31         users = te.user.Select(a => a).ToList();
32     }
33  
34     GridView1.DataSource = users;
35     GridView1.DataBind();
36 }

 

第二種 是利用 Linq 的特性,在下達Select語法後,可以繼續串連Where語法, 
讓多條件查詢變得更簡單,有Interllsence,並且在設計階段就可以知道語法有沒有錯

01 ////示範:多條件查詢
02 using (TestEntities te = new TestEntities())
03 {
04     ////寫法二
05      
06     ////先設定查詢物件
07     var users = te.user.Select(a => a);
08                 
09     if (!string.IsNullOrEmpty(TextBoxId.Text))
10     {
11         int id = int.Parse(TextBoxId.Text);
12         users = users.Where(a => a.user_id == id);
13     }
14      
15     if (!string.IsNullOrEmpty(TextBoxName.Text))
16     {
17         users = users.Where(a => a.user_name == TextBoxName.Text);
18     }
19  
20     if (!string.IsNullOrEmpty(TextBoxAddress.Text))
21     {
22         users = users.Where(a => a.user_address == TextBoxAddress.Text);
23     }          
24  
25     GridView1.DataSource = users;
26     GridView1.DataBind();
27 }

 

在導入 EntityFramework 或 Linq to Sql 後,對資料庫的查詢及操作變得更簡單快速了, 
之後有機會在來分享一下 EntityFramework 更進階的應用,像是 關聯式資料查詢、物件間的傳遞、如何利用 Entity Framework 實做三層式架構 等, 
希望可以有更多人導入並一起研究討論囉~~

你可能感兴趣的:(framework)