I see that the question's been asked several times of how to set the command timeout for long-running queries with Entity Framework. The problem I'm running into now is that the query that gets run against the server doesn't really take that long to execute and return.
Here's the code that runs the query:
var records = (from c in _context.Set<CompletedQuiz>()
where c.FarmId == _entityId && c.ToolboxId == _toolboxId
group c by new { c.UserId, c.LessonId } into g
select g).ToList()
.Select(c => new {
UserId = c.Key.UserId,
LessonId = c.Key.LessonId,
NumQuestions = c.Max(n => n.TotalNumQuestions),
NumLessons = c.Select(l => l.LessonId).Distinct().Count(),
Start = c.Min(s => s.LogonDateTime),
End = c.Max(e => e.LogoffDateTime),
MaxScore = c.Max(s => s.Score),
Passed = c.Any(p => p.Passed)
});
I'm selecting from a fairly simple view called CompletedQuizzes, and grouping on the record ids for users and lessons. I've run this with SQL Profiler running to capture the actual query that's executed; if I run that exact same query in SSMS, it runs almost instantly (<0 seconds). However, running from my application will often exceed the default command timeout of 30 seconds. I put a breakpoint on the line that's shown above, and I added the call to .ToList() to make sure that the query is executed immediately.
What else should I be checking as a possible culprit here?
EDIT:
I still don't understand why the code above takes so long to execute, but I reworked it using using Linq extension methods, and now it runs as fast as I would expect. Here's what it looks like now:
var records = _context.Set<CompletedQuiz>()
.Where(c => c.FarmId == _entityId && c.ToolboxId == _toolboxId)
.GroupBy(c => new { c.UserId, c.LessonId })
.Select(c => new {
UserId = c.Key.UserId,
LessonId = c.Key.LessonId,
NumQuestions = c.Max(n => n.TotalNumQuestions),
NumLessons = c.Select(l => l.LessonId).Distinct().Count(),
Start = c.Min(s => s.LogonDateTime),
End = c.Max(e => e.LogoffDateTime),
MaxScore = c.Max(s => s.Score),
Passed = c.Any(p => p.Passed)
});
I guess at this point I would adjust my question to why is the query generated by the second block of code executed so much more quickly from my application?
_context.Set<CompletedQuiz>().AsNoTracking().