简体   繁体   English

使用Include()优化EF Core查询

[英]Optimize EF Core query with Include()

I have following query within my project and it is consuming lot of time to execute. 我的项目中有以下查询,它消耗大量时间来执行。 I am trying to optimize it, but not able to successfully do it. 我正在尝试对其进行优化,但无法成功实现。 Any suggestions would be highly appreciated. 任何建议将不胜感激。

_context.MainTable
.Include(mt => mt.ChildTable1)
.Include(mt => mt.ChildTable1.ChildTable2)
.Include(mt => mt.ChildTable3)
.Include(mt => mt.ChildTable3.ChildTable4)
.SingleOrDefault(
        mt =>
        mt.ChildTable3.ChildTable4.Id == id 
        &&
        mt.ChildTable1.Operation == operation
        && 
        mt.ChildTable1.Method = method
        && 
        mt.StatusId == statusId);

Include() gets translates to join and you are using too many joins in the code. Include()获取转换为联接,而您在代码中使用了太多联接。 You can optimize indexes with the help of DB engine execution plan. 您可以借助数据库引擎执行计划来优化索引。

I suggest you not to use all Include in one go. 我建议您不要一次使用所有“ Include instead, you break the query and apply Include one by one. 相反,您打断查询并逐个应用“ Include I meant you apply Include, get the result and then apply the Include again and so..By having more than two Include` affect the performance. 我的意思是您应用Include, get the result and then apply the again and so..By having more than two Include, get the result and then apply the Include again and so..By having more than two Include`影响性能。

I Don't see any performance issues with you query. 我看不到查询的任何性能问题。

Since you have a singleOrDefault I would look at uptimizing the database call. 由于您具有singleOrDefault,因此我将着眼于优化数据库调用。 If you have analytics tools available then in SQL Server Management Studio then you choose tools > Sql Server Profiler. 如果您有可用的分析工具,则在SQL Server Management Studio中选择工具> Sql Server Profiler。 Get query into SQL Server Management Studio, mark the query and choose "Analyse Query in Database Engine Tuning advisor" 获取对SQL Server Management Studio的查询,标记查询并选择“在数据库引擎优化顾问中分析查询”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM