疯狂查询需要一些反馈

Cra*_*erz 2 c# linq linq-to-entities

        var query =context.Categories.Include("ChildHierarchy")
             .Where(c =>
                 context.CategoryHierarchy.Where(ch => ch.ParentCategoryID == ch.ParentCategoryID)
                 .Select(ch => ch.ChildCategoryID).Contains(c.CategoryID));
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 我需要包含来自另一个Navigation Propery的一些数据(".Include("otherprop")")
  2. 在所有这些之后是否可以选择新的?

谢谢

Eni*_*ity 6

你问题的标题用"疯狂查询"这个词引起了我的兴趣,是的,你是对的,它有点疯狂.

你有一个.Where(...)带有以下谓词的子句:

ch => ch.ParentCategoryID == ch.ParentCategoryID
Run Code Online (Sandbox Code Playgroud)

现在这将永远是真的.所以我想你正在尝试做别的事情.我会对我答案结尾处的内容有所了解.

然后,我对您的查询进行了一些清理,以便更好地了解您正在做的事情.这就是它现在的样子:

var query =
    context
        .Categories
        .Where(c => context
            .CategoryHierarchy
            .Select(ch => ch.ChildCategoryID)
            .Contains(c.CategoryID));
Run Code Online (Sandbox Code Playgroud)

因此,我不建议使用嵌套查询,而是建议在可读性和性能方面可能更好:

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;
Run Code Online (Sandbox Code Playgroud)

这给出了与查询相同的结果,所以希望这是有帮助的.

我确实得到的印象是,您正在尝试进行查询,以便返回每个类别以及它可能具有的任何子类别.如果是这种情况,那么您需要的查询:

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], };
Run Code Online (Sandbox Code Playgroud)

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], };
Run Code Online (Sandbox Code Playgroud)

这就是你要追求的吗?