林克用join分组

本文关键字:分组 join 林克 | 更新日期: 2023-09-27 17:57:52

[Firstid foreignId field]
[1       1         textFirst1]
[2       1         textFirst2]
[3       1         textFirst3]
[4       2         textFirst4]
[5       2         textFirst5]

[Secondid foreignId field]
[1        1         textSec1]
[2        1         textSec2]
[3        2         textSec3]

foreignId引用到同一张表我的问题是如何编写linq2Sql查询来检索以下结果:

[foreignId countFromSecond fieldFromFirst]
[1         2               textFirst1]
[1         2               textFirst2]
[1         2               textFirst3]
[2         1               textFirst4]
[2         1               textFirst5]

换句话说,我想检索几乎第一个没有id的表,但从第二个表

林克用join分组

中检索count

类似这样的东西:

var query =
    from first in db.FirstTable
    select
        new
        {
            first.foreignId,
            countFromSecond = db.SecondTable
                .Where(arg => arg.foreignId == first.foreignId)
                .Count(),
            first.fieldFromFirst
        };