Repository 简化实现多条件查询

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'))

本文转自田园里的蟋蟀博客园博客,原文链接:http://www.cnblogs.com/xishuai/p/repository-query-linq-expression.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值