如何避免将iQueryable转换为List?

时间:2015-07-17 11:33:08

标签: c# linq entity-framework iqueryable

我有以下(工作)代码:

 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<> - 属性

此代码按预期工作,返回用户的所有位置&#39;客户

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

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

由于效果原因,我想跳过列表&lt;&gt; -Step并留在IQueryAble

有可能吗?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

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

之类的事情

答案 2 :(得分:1)

在处理延迟加载MyContext()之后,我要小心使用IQueryAble或IEnumerable。

查询实际上不会被评估,直到它被用于任何调用它的函数,但到那时,上下文将被处理并抛出异常。

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