在設計表單的時候,我們常常會讓使用者去選擇要輸入哪些資料,
然後把條件組合起來去查詢資料,這邊示範兩種利用EntityFramework的多條件查詢寫法
第一種 是利用StingBuilder把字串加起來,這應該也是大家最常用的寫法,
不過這方法要自己知道欄位名稱,也無法在設計階段就知道有沒有錯誤,
當然也沒有IntellSence
02 |
using (TestEntities te = new TestEntities())
|
05 |
StringBuilder sb = new StringBuilder();
|
07 |
if (!string.IsNullOrEmpty(TextBoxId.Text))
|
09 |
sb.Append(" and it.user_id = " + TextBoxId.Text);
|
12 |
if (!string.IsNullOrEmpty(TextBoxName.Text))
|
14 |
sb.Append(" and it.user_name = '" + TextBoxName.Text + "'");
|
17 |
if (!string.IsNullOrEmpty(TextBoxAddress.Text))
|
19 |
sb.Append(" and it.user_address = '" + TextBoxAddress.Text + "'");
|
27 |
users = te.user.Where(sb.ToString().Substring(4)).ToList();
|
31 |
users = te.user.Select(a => a).ToList();
|
34 |
GridView1.DataSource = users;
|