Repository簡(jiǎn)化實(shí)現(xiàn)多條件查詢-創(chuàng)新互聯(lián)

Repository 在做查詢的時(shí)候,如果查詢條件多的話,linq查詢表達(dá)式會(huì)寫(xiě)的很復(fù)雜,比如:

成都創(chuàng)新互聯(lián)公司專注于和田網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供和田營(yíng)銷型網(wǎng)站建設(shè),和田網(wǎng)站制作、和田網(wǎng)頁(yè)設(shè)計(jì)、和田網(wǎng)站官網(wǎng)定制、成都微信小程序服務(wù),打造和田網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供和田網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。
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;
}

可以看到,查詢條件多的話,我們會(huì)寫(xiě)很多的if判斷,代碼看起來(lái)很不美觀,解決方式使用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'))

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

分享文章:Repository簡(jiǎn)化實(shí)現(xiàn)多條件查詢-創(chuàng)新互聯(lián)
瀏覽地址:http://bm7419.com/article2/dscooc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、網(wǎng)站制作、關(guān)鍵詞優(yōu)化搜索引擎優(yōu)化、響應(yīng)式網(wǎng)站、面包屑導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化