惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
雷峰网
雷峰网
GbyAI
GbyAI
Hugging Face - Blog
Hugging Face - Blog
N
Netflix TechBlog - Medium
博客园 - 聂微东
Y
Y Combinator Blog
罗磊的独立博客
博客园_首页
小众软件
小众软件
有赞技术团队
有赞技术团队
爱范儿
爱范儿
F
Fortinet All Blogs
C
Check Point Blog
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
Apple Machine Learning Research
Apple Machine Learning Research
M
MIT News - Artificial intelligence
月光博客
月光博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏

博客园 - 流泉飞石

转载:GridView 空记录时显示 Header 代码重构相关书籍 转:恢复Reflector反编译后资源文件的办法 WPF 回车转Tab实现跳转 C#自定义快捷键实现介绍 C#程序多用户只启动一个进程的方法[转载] C#中自定义快捷键【转载】 转:[WPF] WPF资源收集 分享 转:.NET开发人员必知的八个网站 WatermarkComboBox 和 WatermarkTextBox 转:c#中线程访问winform控件的若干问题 [转] DotNet资源站点汇总 DataKeyNames工作 - 流泉飞石 - 博客园 转:功能很强大的UIHelper类 转:动态修改webservice地址 转:CS结构软件自动升级实现 几个很好的url重写工具 asp.net获取应用程序路径 - 流泉飞石 - 博客园 SqlServer 查询sql执行时间
转:ADO.Net Entity Framework : (七) 多條件查詢
流泉飞石 · 2010-06-17 · via 博客园 - 流泉飞石

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

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

02using (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 + "'");
25    if (sb.Length != 0)
27        users = te.user.Where(sb.ToString().Substring(4)).ToList();
31        users = te.user.Select(a => a).ToList();
34    GridView1.DataSource = users;
35    GridView1.DataBind();

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

02using (TestEntities te = new TestEntities())
07    var users = te.user.Select(a => a);
09    if (!string.IsNullOrEmpty(TextBoxId.Text))
11        int id = int.Parse(TextBoxId.Text);
12        users = users.Where(a => a.user_id == id);
15    if (!string.IsNullOrEmpty(TextBoxName.Text))
17        users = users.Where(a => a.user_name == TextBoxName.Text);
20    if (!string.IsNullOrEmpty(TextBoxAddress.Text))
22        users = users.Where(a => a.user_address == TextBoxAddress.Text);
25    GridView1.DataSource = users;
26    GridView1.DataBind();

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