Pravin .Kadam
Pravin .Kadam

Reputation: 99

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);

Upvotes: 2

Views: 2527

Answers (2)

Vivek Nuna
Vivek Nuna

Reputation: 1

Include() gets translates to join and you are using too many joins in the code. You can optimize indexes with the help of DB engine execution plan.

I suggest you not to use all Include in one go. instead, you break the query and apply Include one by one. I meant you apply Include, get the result and then apply theIncludeagain and so..By having more than twoInclude` affect the performance.

Upvotes: 1

Thomas Koelle
Thomas Koelle

Reputation: 3742

I Don't see any performance issues with you query.

Since you have a singleOrDefault I would look at uptimizing the database call. If you have analytics tools available then in SQL Server Management Studio then you choose tools > Sql Server Profiler. Get query into SQL Server Management Studio, mark the query and choose "Analyse Query in Database Engine Tuning advisor"

Upvotes: 0

Related Questions