Search code examples
c#entity-frameworklambdaiqueryabledeferred-execution

Execute IQueryable after it's being done building


I want to build filters on IQueryable depending on user input and execute the query only at the end. I'm trying to understand concept behind and if this is going to work as expected.

Will the query below hit database on return fetchedWorkflowLogs.ToList() in the example below?

// Partition latest record for Instance
IQueryable<WorkflowLog> fetchedWorkflowLogs 
                                        = this._workflowLog_repo
                                            .GetAll()
                                            .GroupBy(log => log.ID)
                                            .Select(
                                                grp => new
                                                {
                                                    grp = grp,
                                                    MaxID = grp.Max(log => log.ID)
                                                }
                                            )
                                            .SelectMany(
                                                temp0 => temp0.grp,
                                                (temp0, log) => new
                                                {
                                                    temp0 = temp0,
                                                    log = log
                                                }
                                            )
                                            .Where(temp1 => (temp1.log.ID == temp1.temp0.MaxID))
                                            .Select(temp1 => temp1.log);

// .. some more filters                                         

// Last filter
// Filter by Project
if (model.ProjectID != null)
{
    fetchedWorkflowLogs.Where(record => record.Project.ID == model.ProjectID);
}

return fetchedWorkflowLogs.ToList();

Solution

  • Agree with David. if GetAll() returns IQueryable, and you return fetchedWorkflowLogs.ToList() will result in the linq query being evaluated, and the query will hit database. It's the best if you can debug and step through, and writing a test could help you if execuing program directly is difficult.