我在通过 Web 应用程序运行的 EF 查询 和运行 Profiler 生成的 T-SQL 直接进入 SQL 查询窗口 之间存在一些性能测量问题。
以下是我通过 Web 应用程序执行的 EF 查询:
IEnumerable<application> _entityList = context.applications
.Include(context.indb_generalInfo.EntitySet.Name)
.Include(context.setup_budget.EntitySet.Name)
.Include(context.setup_committee.EntitySet.Name)
.Include(context.setup_fund.EntitySet.Name)
.Include(context.setup_appStatus.EntitySet.Name)
.Include(context.appSancAdvices.EntitySet.Name)
.Where(e => e.indb_generalInfo != null);
if (isIFL != null)
_entityList = _entityList.Where(e => e.app_isIFL == isIFL);
int _entityCount = _entityList.Count(); // hits the database server at this line
在 SQL Profiler 中跟踪上述 EF 查询时,它显示它执行了大约 221'095 毫秒。 (applications 表有 30,000 多条记录,indb_generalInfo 有 11,000 多条记录,appSancAdvices 有 30,000 多条记录)。
但是,当我从 Profiler 复制 T-SQL 并直接从查询窗口运行它时,它只需要大约 4'000 毫秒。
为什么会这样?
最佳答案
此查询中的毒液在第一个词中:IEnumerable<application>
.如果将其替换为 var
(即 IQueryable
)查询将被转换为 SQL,直到并包括最后一个 Count()
。 .这将花费更少的时间,因为传输的数据量减少到几乎为零。
此外,正如 bobek 已经提到的,您不需要 Include
因为你只数 context.applications
项目。
除此之外,您总会注意到使用像 Entity Framework 这样的 ORM 的开销。
关于c# - Entity Framework 和 SQL Server Profiler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17472756/