LINQ 连接表和计数组

LINQ join tables and count groups

我正在尝试为我的 Entity Framework 连接编写执行此 SQL 的 linq 查询:

SELECT 
    l.Site_Name, COUNT(*)
FROM 
    vw_Subnet s
INNER JOIN 
    vw_Lab_Space l ON l.Lab_Space_id = s.Lab_Space_Id
WHERE 
    s.Lab_Space_Id IS NOT NULL 
    AND s.MM_Space_Id IS NOT NULL
GROUP BY 
    l.Site_Name
ORDER BY 
    2 DESC

但我想不出正确的语法。没有 WHERE 子句我试过这个,但它实际上并没有像我看到的所有例子那样做 GROUP BY 部分暗示它应该是:

from l in db.vw_Lab_Space.AsNoTracking()
join s in db.vw_Subnet.AsNoTracking()
  on l.Lab_Space_Id equals s.Lab_Space_Id into joined
select new SiteCount {
    Site = l.Site_Name,
    Count = joined.Count()
};

我要找回 SiteCount 具有重复站点值的

你忘了写你要实现的规范,不过好像是下面的。

您有一系列 vwLabSpace,其中每个 vwLabSpace 都有一个 LabSpaceId 和一个 SiteName。

您还有一系列 vwSubnet,其中每个 vwSubnet 都有一个 LabSpaceId

您想在公共 LabSpaceId 上加入这两个序列。然后你想将连接的元素分组到具有相同 SiteName 值的元素组中(因此一组中的每个元素都具有相同的 SiteName)

最终结果应该是一个列表,其中包含每个组的公共站点名称以及每个组中的元素数量。

婴儿学步:

// your two sequences:
IQueryable<VwLabSpace> vwLabSpaces = myDbContext.VwLabSpaces;
IQueryable<VwSubNet> vwSubNets = myDbContext.VwSubNext;

// join on common LabSpaceId
var joinedItems = vwLabSpaces.Join(vwSubNets, // join the two sequences
    vwLabSpace => vwLabSpace.LabSpaceId,      // from every vwLabSpace take the LabSpaceId
    vwSubNet => vwSubNet.LabSpaceId,          // from every vwSubNet take the LabSpaceId
    (vwLabSpace, vwSubNet => new              // when they match make a new
    {                                         // joined object containing
        VwLabSpace = vwLabSpace,              // both matching objects
        VwSubNet = vwSubNet,
    });

    // make groups of joinedItems that have same SiteName
    var groupsWithSameSiteName = joinedItems
        .GroupBy(joinedItem => joinedItem.VwLabSpace.SiteName);

    // finally: get the common SiteName (= Key) and count the elements of each group
    var result = groupsWithSameSiteName
        .Select(group => new        // from every group make one new object
        {                           // with two properties:
            SiteName = group.Key,   // the common SiteName of all elements in the group
            Count = group.Count(),  // and the number of elements in the group
        });

TODO:如果需要的话,做一个大的 LINQ 语句。由于延迟执行,这不会有什么不同。

因为您只使用每个连接项目的 SiteName,所以您不必组合完整的连接对象:

// join on common LabSpaceId
var joinedItems = vwLabSpaces.Join(vwSubNets, // join the two sequences
    vwLabSpace => vwLabSpace.LabSpaceId,      // from every vwLabSpace take the LabSpaceId
    vwSubNet => vwSubNet.LabSpaceId,          // from every vwSubNet take the LabSpaceId
    (vwLabSpace, vwSubNet) =>                 // when they match
        vwLabSpace.SiteName);                 // keep the SiteName