在DbContext上构建过滤器 [英] Building filters on DbContext
问题描述
我有一个ASP .Net Core 2.1 Web Api.我想知道是否存在优雅的解决方案",用于基于查询字符串在DbContext上构造过滤器?所以...说我有一个[可选]查询字符串:
I have an ASP .Net Core 2.1 Web Api. I was wondering if there is an "elegant solution" for constructing filters on my DbContext based on query strings? So... say I have one [optional] query string:
// GET: api/Accounts
[HttpGet]
public IEnumerable<File> GetAccount([FromQuery] bool? isActive)
{
if (isActive.HasValue)
return _context.Accounts.Where(a => a.IsActive == isActive.Value);
else
return _context.Accounts;
}
足够简单...但是说我有很多(可选)查询字符串:
Simple enough... But say I have a number of (optional) query strings:
// GET: api/Accounts
[HttpGet]
public IEnumerable<File> GetAccount([FromQuery] bool? isActive, [FromQuery] string type, [FromQuery] int? agentId, [FromQuery] bool? someOtherFilter)
{
}
如您所见,构建过滤器现在变得更加困难,因为可以组合使用过滤器,具体取决于提供的过滤器.我可以检查第一个查询字符串是否具有值,如果有,执行过滤器并将结果保存到temp变量中.然后,我可以检查下一个查询字符串(如果有一个值),然后对temp变量执行该过滤器,依此类推.但这听起来会很慢...还有其他建议吗?谢谢...
As you can see, constructing the filters now gets harder, because there can be a combination of filters, depending which ones have been supplied. I could check if the first query string has a value, if it does, perform the filter and save the results into a temp variable. Then I could check the next query string, if that has a value, then perform that filter on the temp variable, and so on and so on. But that sounds like it's going to be slow... Any other suggestions? Thanks...
推荐答案
您可以使用if/else
检查所有可选值:
You can check all your optional values with 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中,您可以在Where()
方法内检查null
:
or in linq to sql you can check for null
inside your Where()
method:
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);
这篇关于在DbContext上构建过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!