linq to sql优化了一个具有多个连接的组

时间:2010-12-20 22:31:28

标签: c# linq-to-sql group-by

我需要帮助生成更有效的LINQ查询:

Table: Positions
-PositionID
-Name

Table: Person
-PersonID
-Name, etc...

Table: PersonPosition
-PersonID
-PositionID

我需要一个结果集,将分配给每个职位的人员分组:

PositionID  Person
1           John
            Bob
            Frank

2           Bill
            Tom
            Frank, etc...

我首先想到的是这个LINQ查询:

from perspos in PersonPositions
join pers in Persons            on perspos.PersonID equals pers.PersonID 
group pers by perspos.PositionID into groups
select new {groups.Key, groups}

哪个效果很好,但会生成以下SQL:

SELECT [t0].[PositionID] AS [Key]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
GROUP BY [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 3
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 4
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

-- Region Parameters
DECLARE @x1 Int = 5
-- EndRegion
SELECT [t1].[PersonID], [t1].[UserID], [t1].[Firstname], [t1].[Lastname], [t1].[Email], [t1].[Phone], [t1].[Mobile], [t1].[Comment], [t1].[Permissions]
FROM [PersonPosition] AS [t0]
INNER JOIN [Person] AS [t1] ON [t0].[PersonID] = [t1].[PersonID]
WHERE @x1 = [t0].[PositionID]
GO

on and on...

是否有更好的LINQ查询转换为更高效的SQL语句?

2 个答案:

答案 0 :(得分:1)

我很确定你必须加入表并选择结果,然后调用.AsEnumerable(),然后分组:

(from perspos in PersonPositions
 join pers in Persons
 on perspos.PersonID equals pers.PersonID
 select new { perspos.PositionID, Person = pers })
.AsEnumerable().GroupBy(p => p.PositionID, p => p.Person);

答案 1 :(得分:1)

您应该已经在数据库中定义了关系,也在dbml上定义了关系。

当你不需要时,避免加入;他们真的很乏味。让LINQ-to-SQL为您完成此任务。这样的事情应该有效:

var data = context.PersonPositions
    .Select(pos => new { pos.PositionID, pos.Person });
return data.GroupBy(pos => pos.PositionID);

return context.Positions.Select(pos => 
    new { pos, pos.PersonPositions.Select(pp => pp.Person).ToList() }).ToList();