【问题标题】:IQueryable Multiple Queries executed when applying multiple where clause应用多个 where 子句时执行的 IQueryable 多个查询
【发布时间】:2015-08-20 23:22:59
【问题描述】:

我有以下 IQueryable where,有多个评估,但我注意到这导致对服务器执行 9 个查询?实际上什么时候应该只有一个?

var datafound = db.CustomersData
    .Where(x => x.EntryDate == eod.EntryDate);

if (!string.IsNullOrWhiteSpace(eod.Type))
    datafound = datafound.Where(x => x.Type == eod.Type);

if (!string.IsNullOrWhiteSpace(eod.LastName))
    datafound = datafound.Where(x => x.LastName.Contains(eod.LastName));

if (!string.IsNullOrWhiteSpace(eod.Address))
    datafound = datafound.Where(x => x.Address.Contains(eod.Address));

if (!string.IsNullOrWhiteSpace(eod.BuildingName))
    datafound = datafound.Where(x => x.BuildingName.Contains(eod.BuildingName));

    .....
    .....


return datafound.ToList();

【问题讨论】:

  • 您是如何得出这样的结论的?这会导致 9 个查询?
  • @TravisJ 我同意 - 我看不出这将如何执行 9 次,即使 CustomersData 不是 IQueryable。我们能看到它正在运行的查询吗?
  • 不适用于IQueriable。如果你的“...”没有隐藏任何额外的逻辑。 ToList() 将“执行”(如果我可以这么说的话)您的实际查询。
  • 应该是一个查询,除非你在debug中加断点。
  • ... 与查询生成器的风格相同。我漏掉了,因为它重复了同样的事情

标签: c# asp.net linq asp.net-mvc-4


【解决方案1】:

该逻辑在 .ToList() 之前有一个 fillinViewBag 方法,在 fillinViewBag 内部有几个对 .sum .avg 等的评估。

fillinViewBag 方法只需要 .Tolist() 之前而不是之后,这使得 Query 的执行只需要 1 次,而 fillinViewBag 方法只处理内存中的数据。

感谢您的快速反馈。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2017-06-26
    相关资源
    最近更新 更多