首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何避免将iQueryable转换为列表?

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

Stack Overflow用户
提问于 2015-07-17 11:33:07
回答 3查看 155关注 0票数 1

我有以下(工作)代码:

代码语言:javascript
复制
 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<>-Properties

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

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

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

由于性能原因,我想跳过列表<>-步骤,停留在IQueryAble

有可能吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-07-17 11:35:40

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

然后你可以做一些像allLocations = currentLogin.Customers.SelectMany(c => c.Locations).AsQueryable()这样的事情。

票数 1
EN

Stack Overflow用户

发布于 2015-07-17 11:40:29

如果不使用foreach循环来完成整个工作,可以使用SelectMany(https://msdn.microsoft.com/en-us/library/bb534336(v=vs.100%29.aspx)? ),这样就可以将一切都保持为IEnumerable

代码语言:javascript
复制
using (MyContext context = new MyContext())
{
    Login currentLogin = GetCurrentLogin(context);
    if (currentLogin != null)
    {
        return currentLogin.Customers.SelectMany(c => c.Locations);
    }
}
票数 2
EN

Stack Overflow用户

发布于 2015-07-17 11:52:37

在释放了IQueryAble ()之后,我会小心地使用IEnumerable或MyContext(),因为它们是延迟加载的。

在调用查询的任何函数中使用查询之前,都不会对查询进行实际计算,但到那时,上下文将被释放,异常将被抛出。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31474869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档