var query =context.Categories.Include("ChildHierarchy")
.Where(c =>
context.CategoryHierarchy.Where(ch => ch.ParentCategoryID == ch.ParentCategoryID)
.Select(ch => ch.ChildCategoryID).Contains(c.CategoryID));
问题:
我需要包含其他导航属性(“ .Include(“ other prop”)“)中的一些数据
所有这些之后是否有可能做一个新的选择?
谢谢
最佳答案
您问题的标题使我对“ Crazy Query”字眼感兴趣,是的,您是对的,这有点疯狂。
您有一个带有以下谓词的.Where(...)
子句:
ch => ch.ParentCategoryID == ch.ParentCategoryID
现在,这将永远是正确的。所以我想您正在尝试做其他事情。我将在答案的结尾处有所作为。
然后,我对您的查询进行了一些清理,以更好地了解您的工作。现在是这样的:
var query =
context
.Categories
.Where(c => context
.CategoryHierarchy
.Select(ch => ch.ChildCategoryID)
.Contains(c.CategoryID));
因此,与使用嵌套查询相比,我建议在可读性和性能方面可能会更好:
var query =
from c in context.Categories
join h in context.CategoryHierarchy
on c.CategoryID equals h.ChildCategoryID into ghs
where ghs.Any()
select c;
这将提供与您的查询相同的结果,因此希望这会有所帮助。
确实给人一种印象,您正在尝试执行查询,以返回每个类别以及它可能具有的所有子类别。如果是这种情况,这里是您需要的查询:
var lookup =
(from c in context.Categories
join h in context.CategoryHierarchy
on c.CategoryID equals h.ChildCategoryID
select new { ParentCategoryID = h.ParentCategoryID, Category = c, }
).ToLookup(x => x.ParentCategoryID, x => x.Category);
var query =
from c in context.Categories
select new { Category = c, Children = lookup[c.CategoryID], };
lookup
查询首先对类别和类别层次结构进行联接,以返回所有子类别及其关联的ParentCategoryID
,然后创建从ParentCategoryID
到关联的Category
子列表的查找。现在,查询只需选择所有类别并在
CategoryID
上执行查找即可获得子项。使用
.ToLookup(...)
方法的优点在于,它可以轻松地让您包括没有子类的类别。与使用Dictionary<,>
不同,当您使用没有值的键时,查找不会引发异常-而是返回一个空列表。现在,您也可以重新添加
.Include(...)
调用。var lookup =
(from c in context.Categories
.Include("ChildHierarchy")
.Include("otherprop")
join h in context.CategoryHierarchy
on c.CategoryID equals h.ChildCategoryID
select new { ParentCategoryID = h.ParentCategoryID, Category = c, }
).ToLookup(x => x.ParentCategoryID, x => x.Category);
var query =
from c in context.Categories
.Include("ChildHierarchy")
.Include("otherprop")
select new { Category = c, Children = lookup[c.CategoryID], };
那是你追求的吗?
关于c# - 疯狂查询需要一些反馈,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5058372/