Repository 在做查詢的時(shí)候,如果查詢條件多的話,linq
查詢表達(dá)式會(huì)寫的很復(fù)雜,比如:
江達(dá)ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來市場(chǎng)廣闊!成為成都創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!
public IQueryable<Student> Get(int id, string name, string address, Status? status, DateTime createTime) { var query = _entities; if(id != 0) { query = query.where(x => x.Id == id); } if(!string.IsNullOrWhiteSpace(name)) { query = query.where(x => x.Name.Contains(name)); } if(!string.IsNullOrWhiteSpace(address)) { query = query.where(x => x.Address.Contains(address)); } if(status.HasValue) { query = query.where(x => x.Status == status.Value); } if(createTime != null) { query = query.where(x => x.CreateTime == createTime); } // ... return query; }
可以看到,查詢條件多的話,我們會(huì)寫很多的if
判斷,代碼看起來很不美觀,解決方式使用Expression<Func<T, bool>>
,示例代碼:
using System.Linq.Expressions; public IQueryable<Student> Get(int id, string name, string address, Status? status, DateTime createTime) { Expression<Func<Student, bool>> studentFunc = x => (id == 0 || x.Id == id) && (string.IsNullOrWhiteSpace(name) || x.Name.Contains(name)) && (string.IsNullOrWhiteSpace(address) || x.Address.Contains(address)) && (!status.HasValue || x.Status == status.Value) && (createTime == null || x.CreateTime <= createTime); return _entities.Where(studentFunc); }
生成示例sql
代碼:
SELECT `x`.`id`, `x`.`name`, `x`.`address`, `x`.`status`, `x`.`create_time` FROM `students` AS `x` WHERE (`x`.`id` = 2) AND (`x`.`status` = 0) AND (`x`.`create_time` == '2017-04-25T16:24:29.769+08:00'))
分享文章:Repository簡(jiǎn)化實(shí)現(xiàn)多條件查詢
本文地址:http://jinyejixie.com/article20/jojpco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、網(wǎng)站改版、App開發(fā)、關(guān)鍵詞優(yōu)化、云服務(wù)器、全網(wǎng)營(yíng)銷推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)