我有以下(工作)代码:
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及其对象存在于实体框架中。Customers和Locations是ICollection<>-Properties
此代码按预期工作,从用户的客户返回所有位置
但是正如您所看到的,我将实体customer.Locations添加到List中。
在该函数的末尾,我以IQueryAble的形式返回生成的列表,以便能够继续对结果使用LinQ-Expressions。
由于性能原因,我想跳过列表<>-步骤,停留在IQueryAble中
有可能吗?
发布于 2015-07-17 11:35:40
将List<Location> allLocations更改为IQueryable<Location> allLocations。
然后你可以做一些像allLocations = currentLogin.Customers.SelectMany(c => c.Locations).AsQueryable()这样的事情。
发布于 2015-07-17 11:40:29
如果不使用foreach循环来完成整个工作,可以使用SelectMany(https://msdn.microsoft.com/en-us/library/bb534336(v=vs.100%29.aspx)? ),这样就可以将一切都保持为IEnumerable。
using (MyContext context = new MyContext())
{
Login currentLogin = GetCurrentLogin(context);
if (currentLogin != null)
{
return currentLogin.Customers.SelectMany(c => c.Locations);
}
}发布于 2015-07-17 11:52:37
在释放了IQueryAble ()之后,我会小心地使用IEnumerable或MyContext(),因为它们是延迟加载的。
在调用查询的任何函数中使用查询之前,都不会对查询进行实际计算,但到那时,上下文将被释放,异常将被抛出。
因此,可能是为什么该方法最初将返回的结果填充到List中,因为它强制在上下文仍处于活动状态时对查询进行计算。
https://stackoverflow.com/questions/31474869
复制相似问题