所以你有一个Companies的表,其中每个Company有零个或多个BDetails,每个BDetail都属于一个公司,即外键CompanyId所指的公司:一个简单的一对多关系。
同样,每一个BDetail有零个或多个FDetails,每一个FDetail恰好属于一个BDetail,即外键BDetail所指的BDetail。
对于每家公司,您都需要该公司的名称和该公司的 BDetails 数量。在我看来,您还想要该公司所有 BDetails 的 FDetails 总数。
var result = dbContext.Companies.Select(company => new
{
Name = company.Name,
BDetailIds = dbContext.BDetails
.Where(bDetail => bDetail.CompanyId == company.Id)
.Select(bDetail => bDetail.Id),
})
中间结果:对于每个公司,您都创建了一个对象,该对象包含公司的名称以及所有 BDetails 的 ID
继续 Linq:计算总数:
.Select(company => new
{
Name = company.Name,
// Total1 is the number of BDetails of this Company
Total1 = company.BDetailIds.Count(),
// Total2 is the number of FDetails of all BDetails of this Company
// whenever you need the sub-items of a sequence of items, use SelectMany
Total2 = company.BDetailIds
.SelectMany(bDetailId => dbContext.FDetails.Where(fDetail => fDetail.BankId == bDetailId))
.Count();
});
如果您想要更多的属性而不仅仅是总数:
var result = dbContext.Companies.Select(company => new
{
// Select the company properties that you plan to use:
Id = company.Id,
Name = company.Name,
...
BDetail = dbContext.BDetails
.Where(bDetail => bDetail.CompanyId == company.Id)
.Select(bDetail => new
{
// Select only the bDetail properties of the company that you plan to use
Id = bDetail.Id,
...
// not needed, you know the value:
// CompanyId = bDetail.CompanyId,
FDetails = dbContext.FDetails
.Where(fDetail => fDetail.BankId == bDetail.Id)
.Select(fDetail => new
{
// you know the drill by now: only the properties that you plan to use
Id = fDetail.Id,
...
})
.ToList(),
})
.ToList(),
});