Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Repository simplifies the implementation of multi-conditional query

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

When Repository is doing a query, if there are many query conditions, the linq query expression will be written very complicated, such as:

public IQueryable 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;}

As you can see, if there are many query conditions, we will write a lot of if judgments, the code looks very ugly, the solution is to use Expression, example code:

using System.Linq.Expressions;public IQueryable Get(int id, string name, string address, Status? status, DateTime createTime){ Expression 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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report