我正在尝试做一个相对基本的 SQL 语句来加入和分组一些表并使用聚合函数进行汇总。我会像这样用 SQL 编写它:
select
p.LocationID,
NumReadings = count(*),
MinDate = min(t.[DateTime]),
MaxDate = max(t.[DateTime])
from Station p inner join Data pd on p.LocationID = pd.ReadingLocationID
inner join ApplicationDateTime t on t.ApplicationDateTimeID = pd.DateTimeID
group by p.LocationID
当我在 EF4 中使用下面的 Linq 语句时,它会创建一些可怕的 SQL(见最底部)。有没有更好的方法来做到这一点?显式地执行连接而不是使用 EF 导航属性会使情况变得更糟。
我不关心美学,但看看查询执行,执行格式不佳的 SQL 需要 3-4 倍的时间。
from s in Station
select new DataSummary
{
ReadingLocationID = s.ReadingLocationID,
StationIdentifier = s.StationIdentifier,
NumReadings = s.Data.Count(),
MinDateLoaded = s.Data.Min(d => d.ApplicationDateTime.DateTime),
MaxDateLoaded = s.Data.Max(d => d.ApplicationDateTime.DateTime)
};
这是 SQL(注意:这里还有一些额外的复杂性,例如表示为另一个连接的继承关系,但这只会导致另一个嵌套级别)。
SELECT
[Project3].[LocationTypeID] AS [LocationTypeID],
[Project3].[ReadingLocationID] AS [ReadingLocationID],
[Project3].[LocationIdentifier] AS [LocationIdentifier],
[Project3].[C1] AS [C1],
CAST( [Project3].[C2] AS datetime2) AS [C2],
CAST( [Project3].[C3] AS datetime2) AS [C3]
FROM ( SELECT
[Project2].[ReadingLocationID] AS [ReadingLocationID],
[Project2].[LocationTypeID] AS [LocationTypeID],
[Project2].[LocationIdentifier] AS [LocationIdentifier],
[Project2].[C1] AS [C1],
[Project2].[C2] AS [C2],
(SELECT
MAX([Extent7].[DateTime]) AS [A1]
FROM [dbo].[Data] AS [Extent6]
INNER JOIN [dbo].[ApplicationDateTime] AS [Extent7] ON [Extent6].[DateTimeID] = [Extent7].[ApplicationDateTimeID]
WHERE [Project2].[ReadingLocationID] = [Extent6].[ReadingLocationID]) AS [C3]
FROM ( SELECT
[Project1].[ReadingLocationID] AS [ReadingLocationID],
[Project1].[LocationTypeID] AS [LocationTypeID],
[Project1].[LocationIdentifier] AS [LocationIdentifier],
[Project1].[C1] AS [C1],
(SELECT
MIN([Extent5].[DateTime]) AS [A1]
FROM [dbo].[Data] AS [Extent4]
INNER JOIN [dbo].[ApplicationDateTime] AS [Extent5] ON [Extent4].[DateTimeID] = [Extent5].[ApplicationDateTimeID]
WHERE [Project1].[ReadingLocationID] = [Extent4].[ReadingLocationID]) AS [C2]
FROM ( SELECT
[Extent1].[ReadingLocationID] AS [ReadingLocationID],
[Extent1].[LocationTypeID] AS [LocationTypeID],
[Extent1].[LocationIdentifier] AS [LocationIdentifier],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[Data] AS [Extent3]
WHERE [Extent1].[ReadingLocationID] = [Extent3].[ReadingLocationID]) AS [C1]
FROM [dbo].[ReadingLocation] AS [Extent1]
INNER JOIN [dbo].[Station] AS [Extent2] ON [Extent1].[ReadingLocationID] = [Extent2].[LocationID]
WHERE ([Extent1].[LocationTypeID] = CAST( '1' AS int)) AND ([Extent2].[LineID] = 'ACBB3FDF-116C-4E8E-AA80-B925E4922AC8')
) AS [Project1]
) AS [Project2]
)
帮助!谢谢。