在 Group Join 中使用 Where 子句

Using Where clause in Group Join

请考虑以下 2 个表格:

CategoryID            CategoryName            CategoryModel
-----------------------------------------------------------
1                     Book                       1
2                     Shoe                       2
3                     Glass                      1 

SubCategoryID      SubCategoryName    CategoryID     SubCategoryModel    OtherColumn1       OtherColum2
---------------------------------------------------------------------
1                  Book1              1                   3
2                  Book2              1                   1
3                  Shoe1              2                   2
4                  Shoe2              2                   2

我想要这样的查询:

from a in Category
join b in SubCategory
on a.CategoryID equals b.CategoryID into grpDetail
where a.CategoryModel != b.SubCategoryModel     <----------
select new 
{
     Id = a.CategoryID,
     Count1 = grpDetail.Count(o=>o.OtherColumn1 == 1),
     ...
}

我无法访问 b 上面指定行的问题 id。我该如何编写此查询?

谢谢

将您的查询分成 2 个,首先使用 where 子句进行连接,然后进行分组。

类别和子类别之间存在直接的一对多关系:每个类别都有零个或多个子类别;每个子类别都属于一个类别,即外键 SubCategory.CategoryId 所指的类别。

您想在此外键上加入类别和子类别。您不需要所有匹配的类别-子类别组合,您只需要 Category.CategoryModel 不等于 SubCategory.SubCategoryModel.

的那些

从剩余的记录中,您想要select 几个属性。我在你的 类 中没有看到 属性 GrpDetail,所以我不知道你想要什么。

幸运的是,您提到您的问题在何处:

var result = Categories.Join(SubCategories, // join tables Categories and SubCategories
    category => category.Id,                // from every category take the Id,
    subCategory => subCategory.CategoryId,  // from every subCategory take foreign key CategoryId

    (category, subCategory) => new          // when they match make one new object
    {
       // we need at least Category.CategoryModel and SubCategory.SubCategoryModel
       CategoryModel = category.CategoryModel,
       SubCategoryModel = subCategory.SubCategoryModel,

       // Select other Category properties that you plan to use:
       CategoryId = category.Id,
       ...

       // Select other SubCategory properties that you plan to use:
       ...
})
// we don't want all combinations, only those where
// CategoryModel is not equal to SubCategoryModel
.Where(joinResult => joinResult.CategoryModel != joinResult.SubCategoryModel)

// from the remaining combinations calculate the final result
.Select(joinResult => new
{
    Id = joinResult.CategoryId,
    Count1 = ... // sorry, don't know what property grpDetail does
    ...
});