如何避免将 iQueryable 转换为列表?

How to avoid converting iQueryable to a List?

我有以下(工作)代码:

 List<Location> allLocations = new List<Location>();
 using (MyContext context = new MyContext())
 {
     Login currentLogin = GetCurrentLogin(context);
     if (currentLogin != null)
     {
         foreach (var customer in currentLogin.Customers)
         {
             allLocations.AddRange(customer.Locations);
         }
     }
 }
 return allLocations.AsQueryable();

MyContext 及其对象位于 entity framework 中。 CustomersLocationsICollection<>-Properties

此代码按预期工作,return获取用户客户的所有位置

但是如您所见,我将实体 customer.Locations 添加到 List

在该函数的末尾,我 return 生成的列表为 IQueryAble 以便能够继续对结果使用 LinQ-表达式。

由于性能原因,我想跳过 List<>-Step 并留在里面 IQueryAble

可能吗?

List<Location> allLocations 更改为 IQueryable<Location> allLocations

然后你可以做类似allLocations = currentLogin.Customers.SelectMany(c => c.Locations).AsQueryable()的事情。

如何在没有 foreach 循环的情况下使用 SelectMany 完成整个过程?这样你就可以将所有内容保存为 IEnumerable:

using (MyContext context = new MyContext())
{
    Login currentLogin = GetCurrentLogin(context);
    if (currentLogin != null)
    {
        return currentLogin.Customers.SelectMany(c => c.Locations);
    }
}

在处理 MyContext() 后,我会小心使用 IQueryAble 或 IEnumerable,因为它们是延迟加载的。

查询在调用它的任何函数中使用之前不会被实际评估,但届时上下文将被释放并抛出异常。

因此可能是该方法最初将返回的结果填充到 List 中的原因,因为它强制在上下文仍处于活动状态时评估查询。