LINQ-在方法/类之间使用选定的集合
经过大量搜索,我找不到任何东西可以清楚地描述我为什么会看到这种行为(我想这是我遗漏的一些非常简单的东西——我仍然是一个初学者:) 我有一个方法(RefreshFilter),它将对象(rfp)作为参数。rfp有一个名为“Items”的属性,其类型为List 我有两个对RefreshFilter的调用,如下所示:LINQ-在方法/类之间使用选定的集合,linq,entity-framework,linq-to-objects,Linq,Entity Framework,Linq To Objects,经过大量搜索,我找不到任何东西可以清楚地描述我为什么会看到这种行为(我想这是我遗漏的一些非常简单的东西——我仍然是一个初学者:) 我有一个方法(RefreshFilter),它将对象(rfp)作为参数。rfp有一个名为“Items”的属性,其类型为List 我有两个对RefreshFilter的调用,如下所示: rfp = RefreshFilter(rfp, FilteredBy.Category) rfp = RefreshFilter(rfp, FilteredBy.Industry)
rfp = RefreshFilter(rfp, FilteredBy.Category)
rfp = RefreshFilter(rfp, FilteredBy.Industry)
以下是RefreshFilter方法:
public FilterParams RefreshFilterList(FilterParams rfp, FilteredBy filteredBy)
{
using (myEntity context as new myEntity())
{
itemsInCategory = (from i in context.items
join ic in context.ItemsCategories on i.Id equals ic.items.id
where ic.Categories.Id == '52'
select i).ToList<items>();
rfp.Items = rfp.Items.Intersect(itemsInCategory).ToList<items>();
}
return rfp;
}
public FilterParams RefreshFilterList(FilterParams rfp,FilteredBy FilteredBy)
{
使用(myEntity上下文作为新的myEntity())
{
itemsInCategory=(来自context.items中的i
在i.Id上的context.ItemsCategories中加入ic等于ic.items.Id
其中ic.Categories.Id==“52”
选择i.ToList();
rfp.Items=rfp.Items.Intersect(itemsInCategory.ToList();
}
返回rfp;
}
对RefreshFilter(…)的第一个调用工作正常,并返回一个FilterParams对象,该对象具有包含相交列表的.items属性
对RefreshFilter(…)的第二次调用总是返回一个FilterParams对象,该对象具有.items属性,其中包含一个0个元素的列表(这不是预期的,因为我知道列表中有匹配的元素)
通过一些测试,我相信我已经能够将其缩小到与rfp.Items设置的上下文相关。然而,我一直认为,在上下文之间共享集合的正确方法是将它们选择到集合对象中并传递这些对象,但这些对象似乎仍然以某种方式与初始上下文相关联
谢谢,试试这个:
public FilterParams RefreshFilterList(FilterParams rfp, FilteredBy filteredBy)
{
using (myEntity context as new myEntity())
{
itemIdsInCategory = (from i in context.items
join ic in context.ItemsCategories on i.Id equals ic.items.id
where ic.Categories.Id == '52'
select i.Id).ToList<int>();
rfp.Items = rfp.Items.Where(i => itemIdsInCategory.Contains(i.Id)).ToList<Item>();
}
return rfp;
}
public FilterParams RefreshFilterList(FilterParams rfp,FilteredBy FilteredBy)
{
使用(myEntity上下文作为新的myEntity())
{
ItemIDIncategory=(来自context.items中的i
在i.Id上的context.ItemsCategories中加入ic等于ic.items.Id
其中ic.Categories.Id==“52”
选择i.Id).ToList();
rfp.Items=rfp.Items.Where(i=>itemidIncategory.Contains(i.Id)).ToList();
}
返回rfp;
}
这里我们只比较项目的唯一ID(本例中为int),这也会带来性能优势。谢谢!这样做非常有效(而且更有意义)!在进一步测试之后,这仍然会导致在方法之间传递集合的问题。当我在对RefreshFilter()的第二次调用中对rfp执行LINQ查询时(即来自rfp.Items中的I而不是context.Items中的I…),我在tc.Items.id上收到一个“未设置为对象实例的对象引用”。我的目的是能够在方法之间干净地传递rfp对象,但似乎一旦最初设置了rfp.Items,就无法在设置其值的原始方法之外进行查询(可能是因为使用了上下文)。我应该在第一次调用RefreshFilter()时澄清这一点rfp.Items是这样填写/启动的:rfp.Items=(context.Items select i中的from i).ToList()。提供的答案是问题的正确答案。由于内存中的列表和可查询对象之间无法联接(我完全忽略了这一点),因此会出现额外的错误。