【问题标题】:Filtering IQueryable is bringing back wrong results过滤 IQueryable 会带回错误的结果
【发布时间】:2019-10-07 15:01:41
【问题描述】:

我有一个接受IQueryable<T> 作为参数的方法,称为attachments。在此方法中,我在多个 if 语句中进一步过滤查询。所以我的代码如下:

if(firstCondition)
{
   attachments = attachments.Where(i => i.TestItemId == 1); //3 records in db
   DoWork(attachments);
}
if(secondCondition)
{
   attachments = attachments.Where(i => i.TestItemId == 2); //2 records in db
   DoWork(attachments);
}
...

DoWork();我愿意:

foreach(var items in attachments)
{
   //write attachment name to file here
}

在数据库中,我总共有 5 条记录,在第一个 if 语句中我得到了适当的结果。然而,在第二个if 条件下,我在查询中得到 0 结果。有人可以告诉我哪里出错了。

请注意两个 if 条件都为真。

【问题讨论】:

  • 连接Where 条件会产生AND 查询。因此,这两个组合的结果是SELECT * FROM attachments WHERE TestItemId = 1 AND TestItemId = 2。也许你在想OR
  • @Silvermind 你会建议我采取什么方法?我会在每个 if 条件下创建一个var
  • 您想对您的条件进行 OR 逻辑吗?即id是1还是2?
  • @Chris 如果我只想要 ID 为 1 的项目,则首先进入内部,如果 ID 为 2,则进入第二个项目,因此不需要。我一共有8个条件要满足

标签: c# iqueryable


【解决方案1】:

条件串联

问题在于分配,导致Where 子句串联。

attachments = attachments.Where(i => i.TestItemId == 1);
attachments = attachments.Where(i => i.TestItemId == 2);

以下代码同上:

attachments.Where(i => i.TestItemId == 1).Where(i => i.TestItemId == 2);

如果您从两个 if 中删除 attachments =,则不会有任何问题。

if(firstCondition)
{
   DoWork(attachments.Where(i => i.TestItemId == 1));
}

if(secondCondition)
{
   DoWork(attachments.Where(i => i.TestItemId == 2));
}

【讨论】:

  • 最后一段代码的缺点是它现在正在执行多个 SQL 查询。
  • 在执行多个 SQL 之前。您需要先使用 ToList 来避免这种情况。但是不知道attachments是什么Object,可以是List转换成IQueryable。
  • 我知道,我只是说整个事情可以通过一个电话完成。
  • attachmentis IQueryable<AllAttachments>
【解决方案2】:

您不应为第一个条件分配附件,结果将按 2 个条件过滤: TestItemId == 1 && TestItemId == 2。 => 它总是返回空列表;

【讨论】:

    猜你喜欢
    • 2012-01-09
    • 1970-01-01
    • 2019-10-20
    • 2016-11-30
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2011-09-04
    相关资源
    最近更新 更多