Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Repository simplifies the implementation of multi-conditional query

Shulou Source: shulou.com Published: 2022-06-01 03:35:27 10月06日 Update

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

Tags: Query code condition example complex beautiful way time expression generation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Shulou Information Microsoft Xiaomi Docker