[英]Entity Framework Core - Append conditional where clause
I am trying to add an additional where
clause if a specific queryParameter
is passed in through the url, but it doesn't seem to be working.如果通过 url 传入特定的
queryParameter
where
我正在尝试添加一个额外的where
子句,但它似乎不起作用。 Before I result to doing raw sql, I want to first figure out if I'm doing it correct (documentation seems to be minimal for this as I can't find anything)在我执行原始 sql 之前,我想首先弄清楚我是否做得正确(文档似乎很少,因为我找不到任何东西)
Code minimized for brevity为简洁起见最小化代码
public IActionResult RetrieveAll([FromQuery] string orderByDate, [FromQuery] string taskStatus)
{
try
{
var taskQuery = (from t in _context.Tasks select t);
switch(taskStatus)
{
case "completed":
taskQuery.Where(t => t.IsCompleted == true);
break;
case "notcompleted":
taskQuery.Where(t => t.IsCompleted == false);
break;
}
var tasks = taskQuery.ToList();
return Ok(tasks);
}
catch (Exception ex)
{
return BadRequest();
}
}
I was thinking that simply appending the Where
clause would do it.我在想,简单地附加
Where
子句就可以了。 The code executes the proper code path, but It still comes back with all results.代码执行正确的代码路径,但它仍然返回所有结果。
You define the base query here:您在此处定义基本查询:
var taskQuery = (from t in _context.Tasks select t);
Later, you call the .Where(...)
extension method on the query in order to further filter the query:稍后,您在查询上调用
.Where(...)
扩展方法以进一步过滤查询:
case "completed":
taskQuery.Where(t => t.IsCompleted == true);
break;
However, .Where(...)
doesn't replace the IQueryable
, it returns a new IQueryable
.但是,
.Where(...)
不会替换IQueryable
,它返回一个新的IQueryable
。 As you noted in the comments, you need to replace the query with the new query so that your call to .ToList()
returns the expected results later.正如您在评论中所指出的,您需要用新查询替换查询,以便您对
.ToList()
调用.ToList()
返回预期结果。
Like this:像这样:
taskQuery = taskQuery.Where(t => t.IsCompleted == true);
That's a pretty common pattern for "building up" queries in Entity Framework, so you're definitely on the right track!这是在实体框架中“构建”查询的一种非常常见的模式,因此您绝对走在正确的轨道上!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.