VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • 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

作者:Andy

出处:http://cnblogs.com/andy626

本文版权归作者和博客园共有,欢迎转载。如有问题或建议,请多多赐教,非常感谢。


相关教程