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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。

分享文章:Repository简化实现多条件查询-创新互联
浏览地址:https://www.cdcxhl.com/article2/dscooc.html

成都网站建设公司_创新互联,为您提供定制网站网站制作关键词优化搜索引擎优化响应式网站面包屑导航

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都seo排名网站优化