如何避免将iQueryable转换为List

本文关键字:List 转换 iQueryable 何避免 | 更新日期: 2023-09-27 18:03:17

我有以下(工作)代码:

 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及其对象位于实体框架内。CustomersLocationsICollection<> -性质

此代码按预期工作,从用户的Customers返回所有位置

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

在该函数结束时,我返回生成的列表作为IQueryAble,以便能够继续在结果上使用LinQ -Expressions。

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

有可能吗?

如何避免将iQueryable转换为List

如何通过使用SelectMany来完成没有foreach循环的整个事情?这样你就可以把所有的东西都保存为IEnumerable:

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

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

然后你可以做allLocations = currentLogin.Customers.SelectMany(c => c.Locations).AsQueryable()

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

查询在调用它的函数中使用之前实际上不会被求值,但到那时上下文将被处理并抛出异常。

这可能就是为什么该方法最初将返回的结果填充到List中,因为它强制在上下文仍然活动时对查询进行评估。

相关文章: