使用LINQ取得子类别中的所有项目 [英] Take all items in sub-categories using LINQ
问题描述
我想获取当前类别中的所有项目以及链接到当前项目的所有子类别.当前,我使用递归函数,但是我怀疑可以通过修改查询来完成.主要原因是我想使用.Skip()
和.Take()
,但是如果我仍然必须先使用递归来获取所有类别,这不会有任何区别.
I want to take all items in current category and all sub categories that are linked to current one. Currently I do so using recursive function, but I suspect that it can be done just by modifying query. Main reason is that I want to use .Skip()
and .Take()
but it won't make any difference if I still have to take all categories first using recursion.
public static IQueryable<Models.Item> Items(int id, List<Models.Item> items)
{
if (items == null)
{
items = new List<Item>();
}
ModelDataContext _db = new ModelDataContext();
var currentCategory = _db.Categories.Where(x => x.ID == id).Single();
items.AddRange(currentCategory.Items);
foreach (var c in currentCategory.Categories)
{
Items(c.ID, items);
}
return items.AsQueryable();
}
tl; dr;
具有递归功能,可获取类别和子类别中的所有项目.怀疑仅凭LINQ本身是否有可能.
tl;dr;
Have recursive function that gets all items in category and sub-categories. Wonder if it's possible just by LINQ itself.
推荐答案
EF或LINQ to SQL都不支持急于加载自引用对象.如果他们支持新的HeirarchyID,则有可能,但是,but,这两个平台都没有对此的真正支持.
Neither EF or LINQ to SQL support eager loading of self-referencing objects. It could be possible if they supported the new HeirarchyID, but alas, neither platform has real support for that at this point either.
这篇关于使用LINQ取得子类别中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!