Sqlsugar statement queries all data by default when the query condition is empty, and queries according to the condition if it is not empty

Requirement description: When we query, we need to query according to whether the parameter field passed by the front end is empty. If the field is empty, all will be returned, and if it is not empty, only matching parameters will be returned.

The official documentation of sqlsugar is very detailed, you can also check it out, I just added some comments below to facilitate understanding and
directly upload the code, below we define a query constructor, the meaning of OrIF is the superficial meaning, if if If it is true, add an or statement, the first parameter is to judge whether the field is empty, if it is empty, return false, and the subsequent query statement will not take effect.

 var exp = Expressionable.Create<Tags>();    //查询构造器
exp.OrIF(id.HasValue, it => it.Id == id);           //id为空时则不需要判断,返回全部数据
exp.AndIF(!string.IsNullOrWhiteSpace(tagname), it => it.TagName.Contains(tagname!));   //tagname为空时则不需要后面的判断
 tags = await DbScoped.SugarScope.Queryable<Tags>().Where(exp.ToExpression()).ToListAsync();

We can also write

  var tags = await DbScoped.SugarScope.Queryable<Tags>().Where(
                Expressionable.Create<Tags>().
                OrIF(id.HasValue, it => it.Id == id)
                .AndIF(!string.IsNullOrWhiteSpace(tagname), it => it.TagName.Contains(tagname!))
                .ToExpression()
                ).ToListAsync();

Guess you like

Origin blog.csdn.net/weixin_44442366/article/details/126325789