1. 程式人生 > 實用技巧 >Repository 簡化實現多條件查詢

Repository 簡化實現多條件查詢

Repository 在做查詢的時候,如果查詢條件多的話,linq查詢表示式會寫的很複雜,比如:

 1 public IQueryable<Student> Get(int id, string name, string address, Status? status, DateTime createTime)
 2 {
 3     var query = _entities;
 4     if(id != 0)
 5     {
 6         query = query.where(x => x.Id == id);
 7     }
 8     if(!string
.IsNullOrWhiteSpace(name)) 9 { 10 query = query.where(x => x.Name.Contains(name)); 11 } 12 if(!string.IsNullOrWhiteSpace(address)) 13 { 14 query = query.where(x => x.Address.Contains(address)); 15 } 16 if(status.HasValue) 17 { 18 query = query.where
(x => x.Status == status.Value); 19 } 20 if(createTime != null) 21 { 22 query = query.where(x => x.CreateTime == createTime); 23 } 24 // ... 25 26 return query; 27 }

可以看到,查詢條件多的話,我們會寫很多的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程式碼:

1 SELECT `x`.`id`, `x`.`name`, `x`.`address`, `x`.`status`, `x`.`create_time`
2 FROM `students` AS `x`
3 WHERE (`x`.`id` = 2)
4 AND (`x`.`status` = 0) AND (`x`.`create_time` == '2017-04-25T16:24:29.769+08:00')) 

原文來源:https://www.cnblogs.com/xishuai/p/repository-query-linq-expression.html