I'm experiencing performance issues on some of my queries against EF5 DbContext model in my ASP MVC application.
The queries have many includes over multiple levels of navigation graph, e.g.:
Context.Cars
.Include(c=>c.Model.Maker)
.Include(c=>c.CarOwners.Select(co=>co.Owner))
.Include(c=>c.Navigation1)
.Include(c=>c.Navigation2)
.Include(c=>c.Navigation3)
.ToList();
The first time I run a query it takes about 10 seconds to execute, but when I refresh the page the second time it takes less then a second to execute.
I have run Visual Studio's Performance Analysis tool to see where is the problem and it seems that the GetExecutionPlan() method is consuming most of the time.
I guess the plan is being cached since the second time the query is run (on a page refresh) the query is executed really fast (less then a second).
I understand that the performance of fistp page load is limited since the query is really complicated (the SQL code dumped to DB is about 4k lines long). But the problem is that if I return to the page in an hour or so the query is slow again. It seems like the execution plan cache is cleared somehow? I've checked IIS settings and all application pool recycling setting are turned off.
Just to be clear, I'm not looking for methods to optimize my queries, I'm wondering why my query behaves strangely: first load slow, second load fast and load after one hour again slow.
Any ideas?