您可以使用
if/else
:
[HttpGet]
public IEnumerable<File> GetAccount([FromQuery] bool? isActive, [FromQuery] string type, [FromQuery] int? agentId, [FromQuery] bool? someOtherFilter)
{
var accounts = context.Accounts;
if(isActive.HasValue)
accounts.Where(a => a.IsActive == isActive.Value);
if(!string.IsNullOrEmpty(type))
accounts.Where(a => a.Type == type);
if(agentId.HasValue)
accounts.Where(a => a.AgentId == agentId.Value);
. . .
if(someOtherFilter.HasValue)
accounts.Where(a => a.SomeOtherFilter == someOtherFilter.Value);
}
或者在linq to sql中可以检查
null
在你的内心
Where()
方法:
public IEnumerable<File> GetAccount([FromQuery] bool? isActive, [FromQuery] string type, [FromQuery] int? agentId, [FromQuery] bool? someOtherFilter) =>
context.Accounts.Where(a =>
(!isActive.HasValue || a.IsActive == isActive.Value) &&
(string.IsNullOrEmpty(type) || a.Type == type) &&
(!agentId.HasValue || a.AgentId== agentId.Value) &&
. . .
(!someOtherFilter.HasValue || a.SomeOtherFilter== someOtherFilter.Value);