您好,登錄后才能下訂單哦!
Repository 在做查詢的時候,如果查詢條件多的話,linq
查詢表達式會寫的很復雜,比如:
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; }
可以看到,查詢條件多的話,我們會寫很多的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'))
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。