使用组联接中的Where子句

问题描述 投票:0回答:3

请考虑这两个表:

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。如何编写此查询?

谢谢

c# linq linq-to-sql linq-to-entities
3个回答
1
投票

将查询拆分为2,首先使用where子句进行联接,然后按照分组依据。


1
投票

尝试这样的事情:

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

0
投票

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

您想在此外键上加入Category和SubCategory。您不希望所有匹配的Category-SubCategory组合,仅希望Category.CategoryModel不等于SubCategory.SubCategoryModel的组合。

从其余记录中,您要选择几个属性。我在您的课程中没有看到属性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
    ...
});
© www.soinside.com 2019 - 2024. All rights reserved.