I am using Linq-To-Entities to do a query which is returning only 947 rows but taking 18 seconds to run. I have done a \"ToTraceString\" to get the underlying sql out and ra
Yes. Rewrite the LINQ query. Most LINQ to Entities queries can be written in many different ways, and will be translated to SQL differently. Since you show neither the LINQ nor the SQL nor the query plan, that's about all I can say.
You are smart, though, to try executing the SQL directly. Query compilation can also take time, but you've ruled that out by determining that the SQL accounts for all of the measured time.
Try:
var query = from pe in genesisContext.People_Event_Link
where pe.P_ID == key
from ev in pe.Event // presuming one to many
select ev;
or if pe.Event is one to one:
var query = from pe in genesisContext.People_Event_Link
where pe.P_ID == key
select pe.Event;
return query;
@Craig I couldn't get your query to work as I get an error message saying Type Inference failed in the call to SelectMany.
However I took your advice and went from using the join to an "olde style" pre ANSI type query:
var query = from pe in genesisContext.People_Event_Link
from ev in genesisContext.Events
where pe.P_ID == key && pe.Event == ev
select ev;
Which produces fairly decent sql!
Since 95% of the time is in the nested loops, eliminating them should solve the problem.
There are a few things you can look at:
Are the nested loops necessary. If you wrote a query directly in SQL could you get the same result without using nested loops. If the answer to this is that it could be written without nested loops, what is it in the model or the linq query that is causing it.
Is it an option for you to place some of the logic in views, thereby reducing the complexity of the linq query, and may be removing the need for the nested loops.
Normally I use the SQL server profiler to look at what SQL linq produces, I find this easier especially if you have two screens.
If you still have problems, post your linq query.