我在使用以下实体框架查询时遇到性能问题:
using (MyEntities context = new MyEntities())
{
return context.Companies
.Single(c => c.CompanyId == company.CompanyId)
.DataFile.Sum(d => d.FileSize);
}
在 SQL 探查器中进行跟踪时,我看到以下 SQL 命令:
exec sp_executesql N'SELECT
[Extent1].[DataFileID] AS [DataFileID],
[Extent1].[LocalFileName] AS [LocalFileName],
[Extent1].[ServerFileName] AS [ServerFileName],
[Extent1].[DateUploaded] AS [DateUploaded],
[Extent1].[FileSize] AS [FileSize],
[Extent1].[CompanyID] AS [CompanyID]
FROM [dbo].[DataFile] AS [Extent1]
WHERE [Extent1].[CompanyID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=16
据我所知,所有数据文件行都被返回(超过 10,000 行)到内存中,然后Sum()
正在发生。
编辑:
根据 Patryk 的建议,我已将查询更改为:
using (MyEntities context = new MyEntities())
{
return context.Companies
.Where(c => c.CompanyId == company.CompanyId)
.Select(x => x.DataFiles.Sum(d => d.FileSize))
.Single();
}
SQL 跟踪如下所示:
SELECT TOP (2)
(
SELECT
SUM([Extent2].[FileSize]) AS [A1]
FROM
[dbo].[DataFile] AS [Extent2]
WHERE
[Extent1].[CompanyId] = [Extent2].[CompanyID]
) AS [C1]
FROM
[dbo].[Company] AS [Extent1]
WHERE
[Extent1].[CompanyId] = 16
这要好得多,但是,基本上我只想要这样简单快捷的东西:
SELECT SUM(FileSize) FROM DataFile WHERE CompanyId = 16